有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将位图对象转换为有问题的base64字符串

我有一个简单的应用程序,从相机中抓取图像,然后将其传递给我的onActivityResult()方法。但是,我无法将位图对象编码为base64字符串。Eclipes告诉我byte[] encodedImage = Base64.encode(b, Base64.DEFAULT);行应该是字节[]而不是字符串,所以我认为问题就在这里(因此,它下面的行试图将其强制为字符串对象)。下面是我的代码,这个方法会被触发并显示日志,但数据不是base64

谁能帮帮我吗

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch(requestCode){
        case TAKE_PHOTO_CODE:
            if( resultCode == RESULT_OK ){
                Bitmap thumbnail = (Bitmap) intent.getExtras().get("data");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
                byte[] b = baos.toByteArray(); 
                byte[] encodedImage = Base64.encode(b, Base64.DEFAULT);
                String encodedImageStr = encodedImage.toString();

                Log.e("LOOK", encodedImageStr);


            }
            // RESULT_CANCELED
        break;          
    }               
}

共 (2) 个答案

  1. # 1 楼答案

    数组对象的toString与数组的内容无关

    你应该使用

    String encodedImageStr = new String(encodedImage);
    

    或者你也可以直接去

    String encodedImageStr = Base64.encodeToString(b,Base64.DEFAULT);
    
  2. # 2 楼答案

     Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] byteArray = stream.toByteArray();
                    encode = Base64.encodeBytes(byteArray);
                    try {
                        byte[] decode = Base64.decode(encode);
                        Bitmap bmp = BitmapFactory.decodeByteArray(decode, 0,
                                decode.length);
                        imgview_photo.setImageBitmap(bmp);
                                    }