使用Servlet绘制动态的数字图片
jopen
11年前
以下是web.xml的配置
<?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>GenerateImageServlet</servlet-name> <servlet-class>com.jadyer.servlet.GenerateImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GenerateImageServlet</servlet-name> <url-pattern>/servlet/image</url-pattern> </servlet-mapping> </web-app></span>以下是index.jsp的内容
<%@ page language="java" pageEncoding="UTF-8"%> <%response.sendRedirect(request.getContextPath()+"/servlet/image");%></span></strong></span>以下核心GenerateImageServlet.java的代码
package com.jadyer.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 绘制随机数字图片的Servlet */ public class GenerateImageServlet extends HttpServlet { private static final long serialVersionUID = 760480418450678827L; // 产生的图像的宽度,单位为像素 private final static int WIDTH = 260; // 产生的图像的高度,单位为像素 private final static int HEIGHT = 60; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // 设置输出的内容的类型为JPEG图像 response.setContentType("image/jpeg"); OutputStream os = response.getOutputStream(); createImage(os); os.close(); } /** * 绘制输出整个图形 */ public void createImage(OutputStream os) throws IOException { // 创建一个BufferedIamge对象 BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); // 获取的Graphics2D对象,通过这个对象完成绘图 Graphics2D g = image.createGraphics(); // 绘制背景图 g.setColor(Color.white); g.fillRect(0, 0, WIDTH, HEIGHT); // 画边框 g.setColor(Color.black); g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1); // 设定字体 g.setFont(new Font("Times New Roman", Font.PLAIN, 60)); // 生成随机类 Random random = new Random(); // 取随机产生的6位数字 for (int i = 0; i < 6; i++) { String rand = String.valueOf(random.nextInt(10)); // 将随机产生的数字显示到图象中 g.drawString(rand, 40 * i + 20, 50); } // 生成图像的输出流 ImageOutputStream ios = ImageIO.createImageOutputStream(os); ImageIO.write(image, "jpeg", ios); ios.close(); } }</span></strong></span>