Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 459
Baha' Al-Khateib Avatar asked Dec 22 '15 20:12

Baha' Al-Khateib


1 Answers

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.
like image 176
Paul Vargas Avatar answered Sep 20 '22 04:09

Paul Vargas