6

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?

Baha' Al-Khateib
  • 311
  • 3
  • 13
  • Often having a bit of code you've actually tried will provide better responses. You probably need to decode this and save this as you would any other file. Hopefully that gets you in the right direction. – Marshall Davis Dec 22 '15 at 20:59

1 Answers1

14

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.
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • 1
    Shouldn't that be `str.substring(str.indexOf(",") + 1)`? And if the image's MIME type is `image/jpeg`, you probably don't want to write it as a PNG. – VGR Dec 22 '15 at 21:34
  • ① *Yup*. `+ 1`. Thanks! ;) ② Humm... I don't know. May be *I* want to write to PNG format... but the OP... I don't know. :P – Paul Vargas Dec 22 '15 at 21:53
  • Thanks for your answer I have do this, but I have got some errors, an exception after BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imagedata)); – Baha' Al-Khateib Dec 22 '15 at 22:27
  • What is the exception? You can use http://pastie.org/ for shared the output/code. :) – Paul Vargas Dec 22 '15 at 23:27
  • 8
    As of Java 8 you should use `byte[] imagedata = java.util.Base64.getDecoder().decode(str.substring(str.indexOf(",") + 1));` instead of DatatypeConverter – Lunchbox Mar 12 '19 at 15:01