用Java将base64字符串转换为图像 [英] 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);
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);
//Now try 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?
谢谢
推荐答案
我担心你只需要解码 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..."
string,你必须得到data:image/png;base64,
之后的数据,所以你只得到图像字节然后解码:
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));
这是一段代码,让您了解它的工作原理,但如果您收到一个 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 对象.
- 提取
data
键下的字符串. - 确保以
image/png
开头,以便您知道是 png 图像. - 确保包含
base64
字符串,以便您知道必须对数据进行解码. - 解码
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.
这篇关于用Java将base64字符串转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!