将Bitmap对象转换为有问题的base64字符串

时间:2011-10-18 11:35:36

标签: java android base64 encode

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

答案 0 :(得分:2)

数组对象的toString不对数组的内容做任何事情

你应该使用

String encodedImageStr = new String(encodedImage);

或者您可以直接转到String with

String encodedImageStr = Base64.encodeToString(b,Base64.DEFAULT);

答案 1 :(得分:0)

 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);
                                }
相关问题