1 package com.learn.print; 2 3 4 import java.awt.*; 5 import java.awt.image.BufferedImage; 6 import java.io.*; 7 import javax.imageio.*; 8 import javax.servlet.*; 9 import javax.servlet.http.*; 10 import com.sun.org.apache.commons.collections.Buffer; 11 import com.sun.org.apache.commons.digester.rss.Image; 12 13 public class Mycheckimages extends HttpServlet { 14 15 public static int WIDTH=160; 16 public static int HEIGHT=40; 17 public static int FONT_SIZE=30; 18 19 @Override 20 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 21 throws ServletException, IOException { 22 // TODO Auto-generated method stub 23 //1。设置游览器不缓存数据 24 resp.setHeader("Expires", "-1"); 25 resp.setHeader("Cache-Control", "no-cache"); 26 resp.setHeader("Pragma", "no-cache"); 27 28 //2.创建图片 29 BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); 30 Graphics2D g = (Graphics2D)image.getGraphics(); 31 32 //3.设置背景色 33 g.setColor(Color.red); 34 g.fillRect(0, 0, WIDTH, HEIGHT); 35 36 //4.设置边框及颜色 37 g.setColor(Color.WHITE); 38 g.fillRect(1, 1, WIDTH-2,HEIGHT-2); 39 40 //5.画干扰线 41 g.setColor(Color.black); 42 for(int i=1;i<=4;i++) 43 { 44 int x1=(int)(Math.random()*WIDTH); 45 int y1=(int)(Math.random()*HEIGHT); 46 47 int x2=(int)(Math.random()*WIDTH); 48 int y2=(int)(Math.random()*HEIGHT); 49 50 g.drawLine(x1, y1, x2, y2); 51 } 52 53 //6.产生随机数,并将其写到图片中 54 String s="美国大选元方你怎么看"; 55 g.setColor(Color.red); 56 g.setFont(new Font("宋体",Font.BOLD,FONT_SIZE)); 57 int x=(WIDTH-4*FONT_SIZE)/2; 58 int y=(HEIGHT-FONT_SIZE); 59 for(int i=1;i<=4;i++) 60 { 61 int temp=(int)(Math.random()*10); 62 String word=s.charAt(temp)+""; 63 64 //设置旋转度数 65 int degree=(int)(Math.random()*30); 66 g.rotate(-degree*(Math.PI/180),x,HEIGHT-y); 67 g.drawString(word, x, HEIGHT-y); 68 69 //取消旋转 70 g.rotate(degree*(Math.PI/180),x, HEIGHT-y); 71 x+=FONT_SIZE+3; 72 } 73 74 //7.将图片发送给游览器 75 resp.setContentType("image/jpeg"); 76 ImageIO.write(image, "jpg", resp.getOutputStream()); 77 78 79 } 80 81 @Override 82 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 83 throws ServletException, IOException { 84 // TODO Auto-generated method stub 85 this.doGet(req, resp); 86 } 87 88 }