Convert base64 string to image Convert base64 string to image ajax ajax

Convert base64 string to image


In the server, do something like this:

Suppose

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

Then:

String base64Image = data.split(",")[1];byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

Then you can do whatever you like with the bytes like:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));


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 Importsimport java.io.ByteArrayInputStream;import sun.misc.BASE64Decoder;def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';// tokenize the datadef parts = sourceData.tokenize(",");def imageString = parts[1];// create a buffered imageBufferedImage 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 fileFile 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.


ImageIO.write() will compress the image by default - the compressed image has a smaller size but looks strange sometimes. I use BufferedOutputStream to save the byte array data - this will keep the original image size.

Here is the code:

import javax.xml.bind.DatatypeConverter;import java.io.*;public class ImageTest {    public static void main(String[] args) {        String base64String = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAB5C...";        String[] strings = base64String.split(",");        String extension;        switch (strings[0]) {//check image's extension            case "data:image/jpeg;base64":                extension = "jpeg";                break;            case "data:image/png;base64":                extension = "png";                break;            default://should write cases for more images types                extension = "jpg";                break;        }        //convert base64 string to binary data        byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);        String path = "C:\\Users\\Ene\\Desktop\\test_image." + extension;        File file = new File(path);        try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {            outputStream.write(data);        } catch (IOException e) {            e.printStackTrace();        }    }}