这样的实现方式对JDK版本有要求。
1 package edu.cloud.editmap.utils; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 import java.awt.Graphics2D; 6 import java.awt.image.BufferedImage; 7 import java.io.IOException; 8 import java.util.Random; 9 10 import javax.servlet.ServletOutputStream; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import com.sun.image.codec.jpeg.JPEGCodec; 15 import com.sun.image.codec.jpeg.JPEGImageEncoder; 16 17 public class IdentityCode { 18 private static final long serialVersionUID = -479885884254942306L; 19 20 public static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8', 21 '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 22 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; 23 24 public static Random random = new Random(); 25 26 public static String getRandomString() { 27 StringBuffer buffer = new StringBuffer(); 28 for (int i = 0; i < 4; i++) { 29 buffer.append(CHARS[random.nextInt(CHARS.length)]); 30 } 31 return buffer.toString(); 32 } 33 34 public static Color getRandomColor() { 35 return new Color(random.nextInt(255), random.nextInt(255), random 36 .nextInt(255)); 37 } 38 39 public static Color getReverseColor(Color c) { 40 return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c 41 .getBlue()); 42 } 43 44 public static void createImage(HttpServletResponse response,HttpServletRequest request){ 45 46 47 response.setContentType("image/jpeg"); 48 49 String randomString = getRandomString(); 50 System.out.println(randomString); 51 52 request.getSession().setAttribute("indentity_code", randomString); 53 54 int width = 100; 55 int height = 30; 56 57 Color color = getRandomColor(); 58 Color reverse = getReverseColor(color); 59 60 BufferedImage bi = new BufferedImage(width, height, 61 BufferedImage.TYPE_INT_RGB); 62 Graphics2D g = bi.createGraphics(); 63 g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16)); 64 g.setColor(color); 65 g.fillRect(0, 0, width, height); 66 g.setColor(reverse); 67 g.drawString(randomString, 18, 20); 68 for (int i = 0, n = random.nextInt(100); i < n; i++) { 69 g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1); 70 } 71 72 // 转成JPEG格式 73 try { 74 75 ServletOutputStream out = response.getOutputStream(); 76 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 77 encoder.encode(bi); 78 out.flush(); 79 80 } catch (IOException e) { 81 e.printStackTrace(); 82 } 83 84 } 85 86 }