Servlet realizes dynamic graphics and text combination output

Source: Internet
Author: User
Tags continue http post http request integer root directory
servlet| Dynamic If you are a web developer, you will more or less encounter a situation where a web designer uses a picture when designing a Web page, where the content needs to be dynamically exported, as shown below:

and \\\\ "Hot focus" this name, perhaps a day or two to request to change to "focus interview" and other words, then have to recreate a picture replacement. and the use of text plus background, sometimes not easy to achieve good results. The use of table background chart, the need to carefully adjust the size of the table, and other changes will intentionally or unintentionally affect it, need to carefully debug.


I encountered in a number of projects in the development of Web pages need dynamic graphics and text combined with output, programmers and art often ultimately chose to avoid and compromise, although the usual impact is not small, but after all, the pursuit of perfection with a gap. Then finally came the solution to this article.

Let's take a look at the issues we're trying to solve.

Our problem can be summed up as: There is a picture, such as:

Now we want to dynamically output text such as \\\\ "hotspot Focus" to the top and get a display similar to the following on the Web page:

How HTML displays a picture
Displaying a picture in HMTL is simple:
In addition, we also know that the SRC attribute of the file type is not limited, that is to say is also legal, the same reference servlet: is also valid, and when the browser resolves to the statement, an HTTP request is sent to the target server. By understanding the HTTP protocol, it is possible to know that if Imageservlet makes the correct response content-type to Image/jpeg (which can be done by setting contenttype= "Images/jpeg"), A picture will also be displayed correctly. This principle is also the principle of the implementation of the image data in the database to display on the Web page.

Further use of this principle, when the request to the Imageservlet image, Imageservlet is not a simple send the original image data, but first to the original image data processing, such as in the original picture above the designated position plus text, even to do some processing such as shadow, stereo, etc. Then the processing of the image data stream sent out, then can not get the picture and text after the combination of it?

Based on the above analysis, we get the implementation of this method: in the SRC attribute of calls to implement the above function of the servlet and pass related parameters, such as the background picture path, output text, text output position, font, size, etc., by the servlet text processing, and returns the processed image data, thus displaying the text-added image on the Web page.

Through the servlet to achieve graphics and text combined with output \

The following principles to write a simple servlet implementation code, the servlet can according to the parameters required to pass the text to the picture and return to the browser images combined with the image data, And on the page of the call to display a combination of graphic images (note: The servlet only implements JPG image file processing, do not support GIF):


Package Net.xdevelop.merge;import Javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*; Import Java.awt.*;import java.awt.image.*;import Com.sun.image.codec.jpeg.*;import net.xdevelop.util.paramutil;/** * text in the specified font, color and size, embedded in the specified picture of the specified location, call parameters: * Text: Text to be embedded * imagefile:jpg the virtual path of the picture * x: The starting X coordinate position of the text output * y: The starting y-coordinate position of the text output * FontColor: Font Color (example fontcolor=ffffff) * fontsize: Font size * FontStyle: Font style (italic, bold, etc.) * FontName: Font name (such as Song, Arial, etc.) */public class Textintoimag E extends HttpServlet {private static final String Content_Type = "image/jpeg;charset=gb2312"; public void Init () throws servletexception {}/** Process the HTTP GET request */public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {doPost (request,response);}//-------------------------------------- -------------------------------------------------------/** Process the HTTP Post request */public void DoPost ( HttpServletRequest request, HttpServletResponse RespoNSE) throws Servletexception, IOException {response.setcontenttype (content_type); String text = ""; Text String imagefile = "" to be embedded; The virtual path of the embedded picture int x = 0; coordinates \ int y = 0; String fontcolor = ""; Font Color int fontsize = 0; Font size String FontStyle = ""; Font style (italic, bold, etc.) String fontname = ""; Font name try {//Get parameters (Paramutil class refer to the Paramutil Class code appended below) Text = Paramutil.getparameter (Request, "text"); ImageFile = Paramutil.getparameter (Request, "imagefile"); x = paramutil.getintparameter (Request, "X", 0); y = paramutil.getintparameter (Request, "Y", 0); FontColor = Paramutil.getparameter (Request, "FontColor"); FontSize = Paramutil.getintparameter (Request, "FontSize", 16); FontStyle = Paramutil.getparameter (Request, "FontStyle"); FontName = Paramutil.getparameter (Request, "FontName"); catch (Exception e) {e.printstacktrace ();} Servletoutputstream Output=response.getoutputstream (); if (Imagefile.tolowercase (). EndsWith (". jpeg") | | Imagefile.tolowercase (). EndsWith (". jpg")) {ImageFile = Getservletcontext (). Getrealpath(ImageFile); InputStream ImageIn = new FileInputStream (new File (ImageFile)); Jpegimagedecoder decoder = Jpegcodec.createjpegdecoder (ImageIn); BufferedImage image = Decoder.decodeasbufferedimage (); Graphics G=image.getgraphics (); Sets the color G.setcolor (new color (Integer.parseint (fontcolor,16))); Set font \ Font mfont = new Font (fontname,font.plain,fontsize);//default font \ If (Fontstyle.equalsignorecase ("italic")) mfont= New Font (fontname,font.italic,fontsize); if (Fontstyle.equalsignorecase ("bold")) Mfont=new Font (fontname,font.bold,fontsize); if (Fontstyle.equalsignorecase ("plain")) mfont=new Font (fontname,font.plain,fontsize); G.setfont (Mfont); Output text g.drawstring (text,x,y); Output data stream \ JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (outputs); Encoder.encode (image); Imagein.close (); } output.close (); }}//////////





The code that gets the argument above uses a tool class, which is a class that extends the Request.getparameter () feature:

Package Net.xdevelop.util;import javax.servlet.*;p ublic class Paramutil {/** * Get the parameter value of the name specified in the request, if there is a garbled problem please increase the transcoding part * param request ServletRequest object \ * @param paramname parameter name * @return Returns the value if the variable value exists, otherwise it returns "" */public static String Getparamet ER (servletrequest request, String paramname) {String temp = Request.getparameter (paramname); if (temp!= null &&amp ;!temp.equals ("")) {//If there is a Chinese problem, add transcoding code here, for example: temp = new String (temp.getbytes ("8859_1"), "GB2312"); return temp; else {return "";}} /** * Obtain the int parameter value in Request * @param request ServletRequest object \ * @param the paramname parameter name * @param defaultnum Default value if the value is not returned * @r Eturn returns the value converted to int if the parameter value exists, otherwise returns DEFAULTNUM/public static int Getintparameter (ServletRequest request, String paramname, int defaultnum) {String temp = Request.getparameter (paramname); if (temp!= null &&!temp.equals ("") {int num = Defaultnum; try {num = integer.parseint (temp);} catch (Exception ignored) {} return num;} Defaultnum; } }}///////////




Practical application

Declaring the servlet in Web.xml

<servlet> <servlet-name>textintoimage</servlet-name> <servlet-class> Net.xdevelop.merge.textintoimage</servlet-class></servlet><servlet-mapping> <servlet-name >textintoimage</servlet-name> <url-pattern>/textintoimage</url-pattern></ Servlet-mapping>





Put the Net.xdevelop.merge.TextIntoImage class and Net.xdevelop.util.ParamUtil class into the web-inf/classes/
JSP page call, in this case to put the bg.jpg file into the root directory, sample code:
Continue to improve
There is a paragraph to be sued here. However, there are many places to continue to improve, such as: Add text effect processing (shadow, stereo, relief, etc.), text vertical line, increase the support for GIF files.

This article code downloads: Demo.zip

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.