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.
The JSON string l
InputStream stream = new ByteArrayInputStream(image.getBytes());
should be changed to
InputStream stream = new ByteArrayInputStream(Base64.decode(image.getBytes(), Base64.DEFAULT));
Refer http://developer.android.com/reference/android/util/Base64.html for details on how to do Base64 decoding.
Disclaimer: I have not checked for syntax, but this is how you should do it.
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, 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));
This is a code so you understand how it works, but if you receive a JSON object it should be done the correct way:
data
key.image/png
so you know is a png image.base64
string, so you know that data must be decoded.base64
string to get the image.Here is the working code that converts the Base64 encoded inputStream and writes it to the disk. I spent a few time to make it work correctly. So I hope this helps other developers.
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);
}