Convert base64 string to Image in Java

前端 未结 3 590
猫巷女王i
猫巷女王i 2020-11-29 04:29

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

3条回答
  •  情书的邮戳
    2020-11-29 04:48

    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.

提交回复
热议问题