generate Image - Java 2D Graphics

Java examples for 2D Graphics:Image Captcha

Description

generate Image

Demo Code


//package com.java2s;
import java.util.Random;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;

public class Main {

    public static BufferedImage generateImage(String textCode, int width,
            int height, int interLine, boolean randomLocation,
            Color backColor, Color foreColor, Color lineColor) {

        BufferedImage bim = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = bim.getGraphics();

        // /*w ww  .  j  av a 2s  . co m*/
        g.setColor(backColor == null  getRandomColor() : backColor);
        g.fillRect(0, 0, width, height);

        // 
        Random r = new Random();
        if (interLine > 0) {

            int x = 0, y = 0, x1 = width, y1 = 0;
            for (int i = 0; i < interLine; i++) {
                g.setColor(lineColor == null  getRandomColor() : lineColor);
                y = r.nextInt(height);
                y1 = r.nextInt(height);

                g.drawLine(x, y, x1, y1);
            }
        }

        // 

        // g.setColor(getRandomColor());
        // g.setColor(isSimpleColorColor.BLACK:Color.WHITE);

        // 80%
        int fsize = (int) (height * 0.8);
        int fx = height - fsize;
        int fy = fsize;

        g.setFont(new Font("Default", Font.PLAIN, fsize));

        // 
        for (int i = 0; i < textCode.length(); i++) {
            fy = randomLocation  (int) ((Math.random() * 0.3 + 0.6) * height)
                    : fy;// 
            g.setColor(foreColor == null  getRandomColor() : foreColor);
            g.drawString(textCode.charAt(i) + "", fx, fy);
            fx += fsize * 0.9;
        }

        g.dispose();

        return bim;
    }

    private static Color getRandomColor() {
        Random r = new Random();
        Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
        return c;
    }
}

Related Tutorials