Convert Base64 String to Image in Java

Convert base64 string to image

This assumes a few things, that you know what the output file name will be and that your data comes as a string. I'm sure you can modify the following to meet your needs:

// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;

def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';

// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];

// create a buffered image
BufferedImage image = null;
byte[] imageByte;

BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();

// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);

Please note, this is just an example of what parts are involved. I haven't optimized this code at all and it's written off the top of my head.

Convert base64 string to Image in Java

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.

Convert base64 string to image at server side in java

Your code looks fine. I can suggest however some more debugging steps for you.

  1. Encode your file manually using, for example, this webpage
  2. Compare if String base64 contains exact same content like you've got seen on the page. // if something wrong here, your request is corrupted, maybe some encoding issues on the frontend side?
  3. See file content created under ./src/main/resources/demo.jpg and compare content (size, binary comparison) // if something wrong here you will know that actually save operation is broken

Remarks:

  • Did you try to do .flush() before close?
  • Your code in current form might cause resource leakage, have a look at try-with-resources

Write Base64-encoded image to file

Assuming the image data is already in the format you want, you don't need ImageIO at all - you just need to write the data to the file:

// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
stream.write(data);
}

(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)

If the image data isn't in the format you want, you'll need to give more details.

Convert base64 string to image in Android

     //encode image(from image path) to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(pathOfYourImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

//encode image(image from drawable) to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourDrawableImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

Saving Base64 String to file

Try to use Base64 class from java.util.Base64

byte[] decodedBytes = Base64.getDecoder().decode(base64String);

Or Base64 from org.apache.commons.codec.binary

byte[] decodedBytes = Base64.decodeBase64(base64String);

And you won't need ByteArrayInputStream object

See this link for more detailed answer

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

You can just basically revert your code using some other built in methods.

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

java8 decode image which encoded in base64

You have a space in your encoded string, which is an illegal character in base64. If you remove it, it still generates the same image in the converter you linked to, and can be now decoded by your code as well.

UPDATE:

Some decoders (like the one you linked, or Base64.getMimeDecoder() in Java) ignore illegal characters, others (like Base64.getDecoder()) don't allow them.



Related Topics



Leave a reply



Submit