Java examples for 2D Graphics:Image Captcha
generate Captcha BufferedImage
//package com.java2s; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; public class Main { public static void main(String[] argv) throws Exception { String code = "java2s.com"; System.out.println(genCaptcha(code)); }// www. j av a 2 s . c om private static Random random = new Random(); private static int width = 80; private static int height = 26; private static int lines = 40; public static BufferedImage genCaptcha(String code) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18)); g.setColor(getRandColor(110, 133)); // drowCode(g, code); // for (int i = 0; i <= lines; i++) { drowLine(g); } g.dispose(); return image; } private static Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc - 16); int g = fc + random.nextInt(bc - fc - 14); int b = fc + random.nextInt(bc - fc - 18); return new Color(r, g, b); } private static String drowCode(Graphics g, String code) { int margin = width / code.length(); for (int i = 0; i < code.length(); ++i) { g.setFont(getFont()); g.setColor(getRandColor(0, 100)); g.translate(random.nextInt(3), random.nextInt(3)); g.drawString(String.valueOf(code.charAt(i)), margin * i, 16); } return code; } private static void drowLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl); } private static Font getFont() { return new Font("Fixedsys", Font.CENTER_BASELINE, 18); } }