import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Images extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //利用bufferedImage 构建图片 BufferedImage image=new BufferedImage(120, 25, BufferedImage.TYPE_INT_RGB); Graphics g= image.getGraphics(); setBackground(g); setBorder(g); drawRandomLine(g); drawRandomNum(g); response.setContentType("image/jpeg"); ImageIO.write(image, "jpg", response.getOutputStream()); } /* * 在图片上画字 */ private void drawRandomNum(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.RED); g.setFont(new Font("宋体",Font.BOLD,20)); String date[]={"你","是","我","的","全","世","界","哈","了","都"}; int x=10; for (int i = 0; i < 4; i++) { int index= new Random().nextInt(date.length); g.drawString(date[index], x, 20); x+=30; } } /* * 在图片上画线 */ private void drawRandomLine(Graphics g) { g.setColor(Color.GREEN); for (int i = 0; i < 4; i++) { //起始坐标 int x=new Random().nextInt(120); int y=new Random().nextInt(25); int x1=new Random().nextInt(120); int y1=new Random().nextInt(25); g.drawLine(x, y, x1, y1); } } /* * 在图片上填充颜色 */ private void setBorder(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.WHITE); g.fillRect(1, 1, 118, 23); } /* * 设置背景色 */ private void setBackground(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.BLUE); g.fillRect(0, 0, 120, 25); } }