25

我想将base64编码的字符串转换为位图,这样我就可以把它放在图像视图中,但是会出现错误

D/skia(7490): --- 解码器->解码返回假,位图返回空值

我的代码是:

byte[] imageAsBytes = Base64.decode(imageData);

image.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
4

6 回答 6

51

首先您必须检查要解码的字符串是否有效并且具有要解码的预期值,为此,您可以执行以下操作:

filePath= Environment.getExternalStorageDirectory()
                        + "/SaudiScore/temporary_holder.jpg";
Bitmap selectedImage =  BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
String strBase64=Base64.encodeToString(byteArray, 0);

然后您可以解码刚刚编码的字符串并通过执行以下操作来获取图像:

byte[] decodedString = Base64.decode(strBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
image.setImageBitmap(decodedByte);
于 2013-03-28T13:35:04.423 回答
25
byte[] decodedString = Base64.decode(mBase64string, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
mImageView.setImageBitmap(decodedByte);
于 2016-07-14T10:29:12.377 回答
7
String base = "Base64 string values of some image";

byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);

ImageView image = (ImageView) this.findViewById(R.id.imageView1);

image.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));

试试这个代码。

于 2016-05-17T08:45:12.823 回答
0
 byte[] decodedString = Base64.decode(strBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
image.setImageBitmap(decodedByte);

我正在使用上述解决方案。它总是返回错误,例如解码的 String 为 null,IllegalStateException .. 我所做的只是将其包装在 try catch 中

于 2019-05-09T09:09:31.277 回答
0

这种方法可以帮助:

private void setExistImage(ImageView imageView, String base64String){
    if (!base64String.isEmpty()) {
        byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
        imageView.setImageBitmap(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
    }
}
于 2018-08-19T07:53:30.920 回答
0

将base64字符串解码/转换为图像

    imageBytes = Base64.decode(imageString, Base64.DEFAULT);
    Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0,imageBytes.length);
    image.setImageBitmap(decodedImage);
于 2019-04-16T15:19:18.110 回答