4/17/2008

A sample servlet that dynamically creates images

This is a sample servlet that dynamically generates JPEG images. Currently all image properties are hard-coded, but it should be trivial to provide a jsp form to collect them (e.g., color, font, dimensions, messages). The generated image contains dynamic data such as the appserver name, and OS name.
package javahowto;

import com.sun.image.codec.jpeg.JPEGCodec;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class ImageServlet extends HttpServlet {
private static final int WIDTH = 450;
private static final int HEIGHT = 200;
private static final Color BACKGROUND_COLOR = new Color(100,149,237);
private static final Color COLOR = new Color(0,0,139);
private static final Font FONT = new Font("Times New Roman", Font.BOLD, 46);
private static final Font FOOT_FONT = new Font("Courier", Font.ITALIC, 14);
private static final Color FOOT_COLOR = Color.BLACK;

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("image/jpg");
ServletOutputStream out = response.getOutputStream();
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_INDEXED);
Graphics graphics = image.getGraphics();
graphics.setColor(BACKGROUND_COLOR);
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
graphics.setColor(COLOR);
graphics.setFont(FONT);
graphics.drawString("Hello World!", 10, HEIGHT/2);
graphics.setFont(FOOT_FONT);
graphics.setColor(FOOT_COLOR);
graphics.drawString("Created by " + getServletContext().getServerInfo(), 10, HEIGHT - 30);
graphics.drawString("for http://javahowto.blogspot.com/ on " + System.getProperty("os.name"), 10, HEIGHT - 10);
JPEGCodec.createJPEGEncoder(out).encode(image);
}
}
The web.xml file is as simple as declaring and mapping a servlet:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<servlet>
<servlet-name>image</servlet-name>
<servlet-class>javahowto.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Build the project and deploy the image.war to any web server or appserver. Enter the URL http://localhost:8080/image/ to view the generated image. Here we are using the .war file base name as the default context-root and a / servlet path. I tested it on Glassfish v2 update 1, Tomcat 6, and JBoss-5.0.0.Beta4 successfully, except some redeployment errors on JBoss, which was resolved by deleting the .war and restarting server.

If the appserver is running on a headless server, you may need to set the system property java.awt.headless to true. Also note that a Sun-specific encoder class (com.sun.image.codec.jpeg.JPEGCodec) is used. It is in rt.jar of Sun's JDK, but may not be available in other vendors' JDK like IBM's JDK or BEA's (now Oracle's) JRockit. If a non-Sun Java is used, you will need to use the appropriate encoder class. Unfortunately, there seems to be no portable JPEG encoder class as of JDK 6.



20 comments:

Sateesh said...

Very Nice Post.. Thanku!!! Is there way to convert a HTML text into an Image.....

cialis said...

I, of course, a newcomer to this blog, but the author does not agree

Ramana said...

Thanks ..It was Very useful for a quick test.

Unknown said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Course in Chennai

Java Online Training India

Unknown said...

I enjoyed on reading your blog post. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Please visit my website, Friv 4000 Games is where all the free friv games.
Friv 4000

eMexoT said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

Dot net training in electronic city

Florahmelda said...

Psychology coursework writing services are essential and they have become very popular for those seeking psychology research writing help services since most of them seek Psychology Research Writing Services.

BTree Systems, Software (IT) Training Institute said...

Btreesystems Specializes in Offering Real-time Experience IT training on AWS, ..etc.. No.1 Software (IT) Training Institute in India aws training in chennai
Python training in Chennai
data science training in chennai
hadoop training in chennai
machine learning training chennai

BTree Systems said...

iot training in chennai - IoT Training in Chennai - IoT is the latest trending technology in which most students are literally Interested to start there career. Find the Best IOT Training Institute in Chennai.

DevOps training in chennai - Start to learn the DeVops technology from the Best DeVops training Institute in Chennai.

blue prism training in Chennai - Join the Robotic process automation from the Best Blue Prism Training in Chennai and go forward in your career. The right time to get expert guidance and upgrade your skills.

uipath training in Chennai - Join the path course and training in Chennai a web application course that will help you to schedule, monitor as well as manage the Robots.

microsoft azure training in chennai - Microsoft azure is a course for both freshers and experienced, get trained under the Best Microsoft azure training Institute in Chennai.

BTree Systems said...

iot training in chennai - IoT Training in Chennai - Here is a better opportunity to learn IOT technology, from the Best IoT Training in Chennai. Both off-line and online - courses are going on enroll now.

DevOps training in chennai - DevOps is a technology which is used to develop the system development and provide high software technology.

blue prism training in Chennai - Join the Robotic process automation from the Best Blue Prism Training in Chennai and go forward in your career. The right time to get expert guidance and upgrade your skills.

uipath training in Chennai -Go ahead and start learning the Uipath technology in Chennai with better guidance and training.

microsoft azure training in chennai - Microsoft azure is a course for both freshers and experienced, get trained under the Best Microsoft azure training Institute in Chennai.

Serv said...
This comment has been removed by the author.
David said...
This comment has been removed by the author.
Rajesh Adhikesavan said...
This comment has been removed by the author.
Amrita Bansal said...

I am expecting more interesting topics from you. And this was nice content and definitely, it will be useful for many people.
Datascience
Data Analytics Training
Devops training

BtreeSystem Training said...

iot training in chennai - IoT Training in Chennai - IOT is one of the technology which has a lot of scope at the very same time very less number of skilled empolyees in this technology which means this particular technology will give a huge success rate. Join the Best IOT Training Institute in Chennai now.

Devops training Institute in Chennai - Devops a combination of Development and operations has an better career .Jobs opportunities are there from startup company to big mnc. Start to learn the devops technology soon and secure your job now.

blue prism training in Chennai - If you choose to learn the blue prism or automation tool you are supposed to have the programming language. start to learn the blue prism training from the Best Blue prism training Institute in Chennai.

uipath training in Chennai - ui path technology is one of the fastest developing field which has lot of job opportunities such as software developer, Programmer and lot more. Join the Best Uipath training Institute in Chennai.

microsoft azure training in chennai -Microsoft azure technology is growing and soon it will be competitive aws. So students start to learn microsoft azure now will be well - paid in future. Start to learn microsoft azure training in Chennai.

Chennai IT Training Center

BtreeSystem Training said...

Artificial Intelligence training in chennai - Artificial Intelligence is programming that helps machines to think and work the same as humans. Join the Best AI Training Institute in Chennai
RPA Training Institute in Chennai - RPA robots utilize the user interface to capture data and manipulate applications just like humans do. join the Best RPA Training Institute in Chennai now.

Load runner training in Chennai - Load runner Software is an automated performance and testing product from Hewlett- Packard for examining System behavior performance. Join the Best Load Runner Training Institute in Chennai now.

apache Spark training in Chennai - Apache Spark is an open-source distributed general-purpose cluster-computing framework.Join the Best Apache spark Training in Chennai now.

mongodb training in chennai - MongoDB is one of the leading NoSQL databases and it is quite an interesting option in a row of open sources.Join the Best MongoDB Training in Chennai now.

Chennai IT Training Center

Naveen Yadav said...

Thank you for your valuable content.very helpful for learners and professionals. You are doing very good job to share the useful information which will help to the students . if you are looking for
Best Machine Learning Training in Gurgaon
then Join iClass Gyanseyu

Addons said...

Web Development Company in usa
Mobile app development in usa
Android app development company in usa
ios app development in usa
ionic framework development in usa

Addons said...

small business seo services in usa
ecommerce seo services in usa
b2b seo services in usa
enterprise seo services in usa
professional seo services in usa

BtreeSystem Training said...

UiPath Training in Chennai
Machine Learning Training in Chennai
PHP Training in Chennai