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?
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?
Share Improve this question asked Dec 22, 2015 at 20:55 Baha' Al-KhateibBaha' Al-Khateib 3411 gold badge3 silver badges15 bronze badges 1- 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 Commented Dec 22, 2015 at 20:59
1 Answer
Reset to default 15The 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
- In order to use the class
javax.xml.bind.DatatypeConverter
, you need Java 6 o greater.