BASE64字符串转换成图像在Java中 [英] Convert base64 string to Image in Java
问题描述
我有一个图像发送给我通过一个JSON字符串。我想这个字符串转换成图像在我的Android应用程序,然后显示该图像。
I have an image being sent to me through a JSON string. I want to convert that string into an image in my android app and then display that image.
JSON字符串看起来是这样的:
The JSON string looks like this:
"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."
注:我截断字符串与...
Note: I truncated the string with a ...
我有一个函数,(我认为)的字符串转换成图像。我这样做对吗?
I've got a function that (I think) converts the string into an image. Am I doing this right?
public Bitmap ConvertToImage(String image){
try{
InputStream stream = new ByteArrayInputStream(image.getBytes());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
Log.v("Ben", "Image Converted");
return bitmap;
}
catch (Exception e) {
return null;
}
}
然后,我尝试在我的Android活动像这样
Then I try to display it on my android activity like this
String image = jsonObject.getString("barcode_img");
Bitmap myBitmap = this.ConvertToImage(image);
ImageView cimg = (ImageView)findViewById(R.id.imageView1);
//Just to test, I've used this static image here, and it works fine. I've now commented this out
//cimg.setImageResource(R.drawable.qrcode);
//Now trying setting dynamic image
cimg.setImageBitmap(myBitmap);
然而,当我这样做,什么也不显示。我不明白,在logcat中的任何错误。我究竟做错了什么?
However, when I do this, nothing shows up. I don't get any errors in the logcat. What am I doing wrong?
感谢
推荐答案
我很担心,你需要去code只有Base64的字符串作为获取图像的字节,所以在
I'm worried about that you need to decode only the base64 string to get the image bytes, so in your
"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."
字符串,必须数据后得到的数据:影像\ / PNG; BASE64,
,所以你得到的只是图像的字节数和c他们然后去$ C $:
string, you must get the data after data:image\/png;base64,
, so you get only the image bytes and then decode them:
String imageDataBytes = completeImageData.substring(completeImageData.indexOf(",")+1);
InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));
这是一个code让你了解它是如何工作的,但如果你收到一个JSON对象,它应该做的的正确的方式:
This is a code so you understand how it works, but if you receive a JSON object it should be done the correct way:
- JSON字符串转换为JSON对象。
- 下提取
数据字符串
键。 - 确保与
图像/ PNG启动
,所以你知道是一个PNG图像。 - 确保包含
的base64
字符串,所以你知道,数据必须去codeD。 - 在德$ C C数据$后
的base64
字符串来获取图像。
- Converting the JSON string to a JSON object.
- Extract the String under
data
key. - Make sure that starts with
image/png
so you know is a png image. - Make sure that contains
base64
string, so you know that data must be decoded. - Decode the data after
base64
string to get the image.
这篇关于BASE64字符串转换成图像在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!