1 15 16 package com.jdon.util; 17 18 import java.awt.*; 19 import java.awt.image.*; 20 import java.util.*; 21 import java.io.*; 22 import javax.imageio.*; 23 24 public class RegisterCode { 25 26 public Color getRandColor(int fc, int bc) { Random random = new Random(); 28 if (fc > 255) 29 fc = 255; 30 if (bc > 255) 31 bc = 255; 32 int r = fc + random.nextInt(bc - fc); 33 int g = fc + random.nextInt(bc - fc); 34 int b = fc + random.nextInt(bc - fc); 35 return new Color(r, g, b); 36 } 37 38 public BufferedImage getBufferedImage(int width, int height) { 39 return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 40 } 41 42 public BufferedImage getBufferedImage(InputStream in) throws 43 Exception { 44 return ImageIO.read(in); 45 } 46 47 public void create(int imageWidth, int imageHeight, String randNumber, 48 String fontType, int fontSize, int x, int y, 49 OutputStream out) { 50 BufferedImage image = getBufferedImage(imageWidth, imageHeight); 51 generate(image, randNumber, fontType, fontSize, x, y, out); 52 } 53 54 public void generate(BufferedImage image, String randNumber, 55 String fontType, int fontSize, int x, int y, 56 OutputStream out) { 57 58 try { 59 60 int width = image.getWidth(); 61 int height = image.getHeight(); 62 63 Graphics g = image.getGraphics(); 65 66 g.setColor(getRandColor(200, 250)); 68 g.fillRect(0, 0, width, height); 69 70 g.setFont(new Font(fontType, Font.PLAIN, fontSize)); 72 73 77 g.setColor(getRandColor(160, 200)); 79 Random random = new Random(); 81 for (int i = 0; i < 155; i++) { 82 int x2 = random.nextInt(width); 83 int y2 = random.nextInt(height); 84 int x3 = random.nextInt(12); 85 int y3 = random.nextInt(12); 86 g.drawLine(x2, y2, x2 + x3, y2 + y3); 87 } 88 89 g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 91 20 + random.nextInt(110))); 92 93 g.drawString(randNumber, x, y); 94 95 g.dispose(); 97 98 ImageIO.write( (BufferedImage) image, "JPEG", out); 100 } catch (Exception ex) { 101 System.err.println("generate image error: " + ex); 102 } 103 104 } 105 106 } 107 | Popular Tags |