wood burning stoves 2.0*
The moose likes Servlets and the fly likes Decoding a base64 image dataUrl to a jpeg image in Servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Decoding a base64 image dataUrl to a jpeg image in Servlets" Watch "Decoding a base64 image dataUrl to a jpeg image in Servlets" New topic

Decoding a base64 image dataUrl to a jpeg image in Servlets

shivang sarawagi
Ranch Hand

Joined: Jun 19, 2008
Posts: 147

I am trying to decode a base64 image dataURL to a jpeg image in a servlet & then save it.
The image dataURL I am getting from a web page.

I am using apache.commons.codec.binary.base64 jar

below is my code which I am able to write till now. Please help me how do I do it?

Emanuel Kadziela
Ranch Hand

Joined: Mar 24, 2005
Posts: 186
First of all, what is it you are trying to do? Display an image? Or process a user upload?

If you are trying to display the image, you cannot serve it out as a String as you do here:

Also, the image has to already exist if you want to display it.

If you are trying to let a user upload an image, you cannot process it in the doGet method, since those parameter values are passed in the URL. You have to do it in the doPost method. That's just the beginning, but there are other confusing, unclear things in your post. For example, why is the image data encoded as base 64? Where is this data coming from? There are plenty of tutorial out there on how to build an html form with a file upload field and how to extract the data in the servlet's doPost method, but I'm not sure these apply to your specific circumstances.
Joe Ridener
Ranch Hand

Joined: Jul 16, 2012
Posts: 86
OutputStream out = response.getOutputStream();

try {
ImageIO.write(image, "jpg", out);
} catch(IOException ioe) {
System.err.println("Error writing JPEG file: " + ioe);

Likely the snippet of code you may be looking for. Not sure about base64 as I hardly ever have delt with it...only in practice. However, in that example it is getting the output stream from the response; presumably uploading it would be the next step ( from a Servlet anyway). Instead of outputing a string to the console you write it to a buffered image or engineer some other way to create the first argument of the static method write from class ImageIO. The output stream is from a Servlet so in this example it is getting uploaded to a client browser.
I agree. Here's the link: http://aspose.com/file-tools
subject: Decoding a base64 image dataUrl to a jpeg image in Servlets
Similar Threads
problem while executing the JAR written using ANT
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName DemoJPA
java don't compile my servlet.
display the log/output in JSP or HTML page
Error to import javax.servlet.*