Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for upload custom image and write custom string over image
Previous Home Next

In this Generic Servlet program, a custom image is uploaded through system (harddrive of system) and writes custom string over image.Image must be encored into gif format before sending response to client. Used this jar file into program for encore image into GIF format.

Acme.JPM.Encoders.GifEncoder (here)

Caution: Use gif format image for upload image because the above jar can't handle big pixel of jpg image and through java.io.IOException: too many colors for a GIF Exception.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
		http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <servlet-name>uploadImageServlet</servlet-name>
	<servlet-class>r4r.GenericServlet.uploadImageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>uploadImageServlet</servlet-name>
	  <url-pattern>/uploadImageServlet</url-pattern>
  </servlet-mapping>
  <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Index.jsp

<%-- 
 Document: index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>r4r.co.in-GenericServlet</title>
 </head>
 <body>
 <form action="uploadImageServlet" enctype="multipart/form-data">
  Select File: <input type="file" name="myFile" value="" width="30" /><BR/>
  Enter Title: <input type="text" name="title" value="" size="30" /><BR/>
  <input type="submit" value="Process Image" />
  <input type="reset" value="Reset" />
 </form>
 </body>
</html>

Servlet Program

/*
 * Save as a uploadImageServlet.java
 */
package r4r.GenericServlet;
import java.awt.*;
import java.io.IOException;
import java.util.logging.*;
import javax.servlet.*;
import javax.servlet.http.*;
import Acme.JPM.Encoders.GifEncoder;
/**
 *
 * @author R4R
 */
public class uploadImageServlet extends GenericServlet {

 Frame frame = new Frame();
 Graphics graphics = null;

 @Override
 public void service(ServletRequest req,
	 ServletResponse res)throws ServletException,IOException
 {
  res.setContentType("image/gif"); // response send to client browser
  ServletOutputStream out = res.getOutputStream();

  // Get value form TextField
  String imagePath = req.getParameter("myFile");
  String title = req.getParameter("title");

  try {
frame.addNotify(); // Make frame disable on screen
  //check resource availability
if (imagePath == null) {
 out.println("Resource not available at path : " + imagePath +
	  "<BR>Error: " + HttpServletResponse.SC_NOT_FOUND);
 return;
}
//Creates an image with the specified image resource.
Image image = Toolkit.getDefaultToolkit().createImage(imagePath);
//Track image status 
MediaTracker mt = new MediaTracker(frame); //frame acts as ImageObserver
mt.addImage(image, 0);
mt.waitForAll(); //Load all image

 // Reading image property from ImageObserver
int height = image.getHeight(frame);
int width = image.getWidth(frame);

//Make sure reading Image is valid
if (height <= 0 || width <= 0) {
 out.println("Not a valid image: Error " + HttpServletResponse.SC_NO_CONTENT);
 return;
}

Image offscreen = frame.createImage(width, height);
graphics = offscreen.getGraphics();
// Draw the image to the off-screen graphics context
graphics.drawImage(image, 0, 0, frame);

graphics.setFont(new Font("Monospaced", Font.ITALIC | Font.BOLD, 70));
graphics.drawString(title, 10, 60);

 //Encode the off-screen image into GIF format
GifEncoder encoder = new GifEncoder(offscreen, out);
encoder.encode();
  } catch (InterruptedException ex) {
Logger.getLogger(uploadImageServlet.class.getName()).log(Level.SEVERE,
	 "InterruptedException generate while reading image:", ex);
  } finally {
//free all resource
frame.removeNotify();
graphics.dispose();
out.close();
  }
 }
}
Output of Program
Previous Home Next