java如何生成imagecode
java如何生成imagecode?????
package image; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; public class ImageCode { public static void main(String[] args) throws IOException { generateImageCode(); } public static void generateImageCode() throws IOException { System.out.println("generating image code..."); int height = 22; int width = 68; // 1.创建图片缓存区 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 2.创建绘制环境 Graphics paint = image.getGraphics(); Color c = new Color(200, 150, 255); // 设置画笔 paint.setColor(c); // 画背景 paint.fillRect(0, 0, width, height); // 绘制数字和字母 StringBuffer codes = new StringBuffer(); char[] ch = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890".toCharArray(); Random r = new Random(); int index; for(int i = 0; i < 4; i++) { index = r.nextInt(ch.length); // 设置文本颜色 paint.setColor(new Color(r.nextInt(88), r.nextInt(150), r.nextInt(255))); paint.drawString(ch[index]+"", (i*16)+3, 18); codes.append(ch[index]); } File file = new File("./out.jpg"); ImageIO.write(image, "JPG", file); System.out.println("generate image code successfully"); } }
积沙成塔