Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 string to Image in Java

Tags:

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

like image 496
user952342 Avatar asked Jul 06 '13 19:07

user952342


People also ask

How to convert image into Base64 string in java?

Convert Image File to Base64 Stringbyte[] fileContent = FileUtils. readFileToByteArray(new File(filePath)); String encodedString = Base64. getEncoder(). encodeToString(fileContent);

How to convert Base64 to file in java?

byte dearr[] = Base64. decodeBase64(crntImage); File outF = new File("c:/decode/abc. bmp"); BufferedImage img02 = ImageIO. write(img02, "bmp", outF);

How can I get MIME type from Base64?

'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.


1 Answers

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:

  • 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.
like image 127
Jorge Fuentes González Avatar answered Sep 18 '22 17:09

Jorge Fuentes González