我想将base64编码的字符串转换为位图,这样我就可以把它放在图像视图中,但是会出现错误
D/skia(7490): --- 解码器->解码返回假,位图返回空值
我的代码是:
byte[] imageAsBytes = Base64.decode(imageData);
image.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
首先您必须检查要解码的字符串是否有效并且具有要解码的预期值,为此,您可以执行以下操作:
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);
byte[] decodedString = Base64.decode(mBase64string, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
mImageView.setImageBitmap(decodedByte);
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));
试试这个代码。
byte[] decodedString = Base64.decode(strBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
image.setImageBitmap(decodedByte);
我正在使用上述解决方案。它总是返回错误,例如解码的 String 为 null,IllegalStateException .. 我所做的只是将其包装在 try catch 中
这种方法可以帮助:
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));
}
}
将base64字符串解码/转换为图像
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0,imageBytes.length);
image.setImageBitmap(decodedImage);