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 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; } }
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);
However, when I do this, nothing shows up. I don't get any errors in the logcat. What am I doing wrong?
Thanks
Convert Image File to Base64 Stringbyte[] fileContent = FileUtils. readFileToByteArray(new File(filePath)); String encodedString = Base64. getEncoder(). encodeToString(fileContent);
byte dearr[] = Base64. decodeBase64(crntImage); File outF = new File("c:/decode/abc. bmp"); BufferedImage img02 = ImageIO. write(img02, "bmp", outF);
'function guessImageMime(data){ if(data. charAt(0)=='/'){ return "image/jpeg"; }else if(data. charAt(0)=='R'){ return "image/gif"; }else if(data. charAt(0)=='i'){ return "image/png"; } }' Thanks for your answer.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With