This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Decoding a base64 image dataUrl to a jpeg image in Servlets

 
shivang sarawagi
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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
Posts: 187
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic