Skip to content

Instantly share code, notes, and snippets.

@sjpuas
Created August 13, 2013 02:41
Show Gist options
  • Save sjpuas/6217394 to your computer and use it in GitHub Desktop.
Save sjpuas/6217394 to your computer and use it in GitHub Desktop.
Servlet for decode base64 of images. You would change content type for others type.
package cl.puas.web.servlet;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Base64Servlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String imageBase64 = req.getParameter("base64");
OutputStream out = resp.getOutputStream();
writeOutputStream(imageBase64, out);
resp.setContentType("image/png");
resp.setHeader("Pragma", "");
resp.setHeader("Cache-Control", "");
resp.setHeader("Content-Disposition", "inline; fileName=image.png");
}
private void writeOutputStream(String value, OutputStream outputStream) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
byte[] imgBytes = decoder.decodeBuffer(value);
BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(imgBytes));
ImageIO.write(bufImg, "png", outputStream);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment