图形验证码
有事我们登录需要使用到图形验证码,这里记录方便以后查询使用。
package testVerifyCode; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.imageio.ImageIO; import javax.imageio.stream.FileImageOutputStream; public class verifyCode_Demo { private static final String[][] existCode = new String[10][1]; static { existCode[0][0] = "4-1=";existCode[1][0] = "9-0=";existCode[2][0] = "6+1="; existCode[3][0] = "9-8=";existCode[4][0] = "7-3=";existCode[5][0] = "2+6="; existCode[6][0] = "9x7=";existCode[7][0] = "3+4=";existCode[8][0] = "8x2="; existCode[9][0] = "8+4="; } public static void main(String[] args) throws IOException { String randomCode = generateVerifyCode(); BufferedImage img = generteVerifyCodeImage(randomCode); byte[] data = bufferedImage2ByteArray(img); byte2image(data,"D:sd.png"); } public static void byte2image(byte[] data, String path) throws FileNotFoundException, IOException { if (data.length < 3 || path.equals("")) return; FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));// 打开输入流 imageOutput.write(data, 0, data.length);// 将byte写入硬盘 imageOutput.close(); System.out.println("Make Picture success,Please find image in " + path); } private static String generateVerifyCode() { String code = null; int index = ThreadLocalRandom.current().nextInt(10); code = existCode[index][0]; return code; } private static BufferedImage generteVerifyCodeImage(String code) { Random random = new Random(); // 在内存中创建一副图片 int width = 100; int height = 40; BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 在图片上画一个矩形当背景 Graphics g = img.getGraphics(); g.setColor(new Color(randowNum(random, 110, 250), randowNum(random, 110, 250), randowNum(random, 110, 250))); g.fillRect(0, 0, width, height); for (int i = 0; i < code.length(); i++) { g.setColor(new Color(randowNum(random, 50, 180), randowNum(random, 50, 180), randowNum(random, 50, 180))); g.setFont(new Font("黑体", Font.PLAIN, 30)); char c = code.charAt(i); g.drawString(String.valueOf(c), 10 + i * 20, randowNum(random, height - 15, height - 5)); } // 画随机线 for (int i = 0; i < 2; i++) { g.setColor(new Color(randowNum(random, 50, 180), randowNum(random, 50, 180), randowNum(random, 50, 180))); g.drawLine(randowNum(random, 0, width), randowNum(random, 0, height), randowNum(random, 0, width), randowNum(random, 0, height)); } return img; } private static int randowNum(Random random, int min, int max) { int num = 0; num = random.nextInt(max - min) + min; return num; } public static byte[] bufferedImage2ByteArray(BufferedImage image) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); return baos.toByteArray(); } }