Categories
html image java javascript servlets

Convert DataURL image to image file in java

I am receiving image DataURL in my java servlet it looks like:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...

I need to save it as an image file, how can I do that?

The simplest way1 to do it is as follows:

String str = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...";
byte[] imagedata = DatatypeConverter.parseBase64Binary(str.substring(str.indexOf(",") + 1));
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imagedata));
ImageIO.write(bufferedImage, "png", new File("img.png"));


Notes

  1. In order to use the class javax.xml.bind.DatatypeConverter, you need Java 6 o greater.