Android将base64编码的字符串转换为图像视图

Android将base64编码的字符串转换为图像视图

问题描述:

我想将base64编码的字符串转换为位图,以便可以将其放在图像视图中,但是会出现类似错误

I want to convert base64 encoded string into bitmap so i can put it in image view, but getting error like

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

D/skia(7490): --- decoder->decode returned false and bitmap returns null value

我的代码是:

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

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

必须先检查要解码的字符串是否有效并且具有要解码的预期值,然后才能执行以下操作: :

Firts you have to check that the string you want to decode is vaild and has the intended value to be decoded and to do so, you can do something like below:

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);

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

then you can decode the string that you just encoded and get the image back by doing something like the following:

byte[] decodedString = Base64.decode(strBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
image.setImageBitmap(decodedByte);