我有一个通过JSON字符串发送给我的图像。我想在我的android应用程序中将该字符串转换为图像,然后显示该图像。
JSON字符串如下所示:
"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."
注意:我用...截断了字符串
我有一个(我认为)将字符串转换为图像的函数。我这样做对吗?
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活动中,如下所示
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中没有得到任何错误。我做错了什么?
谢谢
发布于 2013-07-07 03:42:57
InputStream stream = new ByteArrayInputStream(image.getBytes());
应更改为
InputStream stream = new ByteArrayInputStream(Base64.decode(image.getBytes(), Base64.DEFAULT));
有关如何进行Base64解码的详细信息,请参阅http://developer.android.com/reference/android/util/Base64.html。
免责声明:我没有检查语法,但这是你应该怎么做的。
发布于 2014-09-22 03:47:51
下面是转换Base64编码的inputStream并将其写入磁盘的工作代码。我花了一些时间让它正常工作。所以我希望这对其他开发人员有帮助。
public boolean writeImageToDisk(FileItem item, File imageFile) {
// clear error message
errorMessage = null;
FileOutputStream out = null;
boolean ret = false;
try {
// write thumbnail to output folder
out = createOutputStream(imageFile);
// Copy input stream to output stream
byte[] headerBytes = new byte[22];
InputStream imageStream = item.getInputStream();
imageStream.read(headerBytes);
String header = new String(headerBytes);
// System.out.println(header);
byte[] b = new byte[4 * 1024];
byte[] decoded;
int read = 0;
while ((read = imageStream.read(b)) != -1) {
// System.out.println();
if (Base64.isArrayByteBase64(b)) {
decoded = Base64.decodeBase64(b);
out.write(decoded);
}
}
ret = true;
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
errorMessage = "error: " + sw;
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("Cannot close outputStream after writing file to disk!" + sw.toString());
}
}
}
return ret;
}
/**
* Helper method for the creation of a file output stream.
*
* @param imageFolder
* : folder where images are to be saved.
* @param id
* : id of spcefic image file.
* @return FileOutputStream object prepared to store images.
* @throws FileNotFoundException
*/
protected FileOutputStream createOutputStream(File imageFile) throws FileNotFoundException {
imageFile.getParentFile().mkdirs();
return new FileOutputStream(imageFile);
}
https://stackoverflow.com/questions/17506428
复制相似问题