生成一个验证码时,图像中要绘制背景颜色、字符、直线、点等一系列内容,而且要给它们分别绘制颜色,分别用setColor函数给它们绘制了,可我不明白的一点是: 第一次填充图形时,setColor函数绘制了背景颜色,可后来对同一对象多次运用了setColor函数,为什么第二次就是绘制直线、接着绘制点呢?setColor是怎么识别我要绘制的东西呢?
代码:- package com.itheima;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.util.Random;
- import javax.imageio.ImageIO;
- public class CreateCodeImage {
- //随机颜色生成函数
- public static Color getcolor(int a,int b){
- Random r = new Random();
- if(a>255) a=255;
- if(b>255) b=255;
- int red=a+r.nextInt(b-a);
- int green=a+r.nextInt(b-a);
- int blue=a+r.nextInt(b-a);
- return new Color(red,green,blue);//返回RGB颜色
- }
- public static void createimage(){
- String code[] = { "A", "a", "B", "b", "C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k", "L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "Q", "q",
- "R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "W", "w", "X", "x", "Y", "y", "Z", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7",
- "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
- Random r = new Random();
- int width=60,height=20;
- BufferedImage pic=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//新建图片对象
- Graphics g = pic.getGraphics();//得到图形的上下文环境
- g.setColor(getcolor(200,250));//第一次设置图形的填充颜色
- g.fillRect(0,0,width,height);//填充矩形区域
- g.setFont(new Font("Times New Roman",Font.PLAIN,18));//设置图形中的字体样式
- //图形中随机绘出100条干扰直线
- g.setColor(getcolor(160,200));//第二次设置直线颜色
- for (int i=0;i<100;i++){
- int x1 = r.nextInt(width);
- int y1 = r.nextInt(height);
- int x2 = r.nextInt(15);
- int y2 = r.nextInt(15);
- g.drawLine(x1,y1,x1+x2,y1+y2);
- }
- //图形中随机绘出100个干扰点
- g.setColor(getcolor(120,240));//第三次设置点的颜色,setColor函数怎么识别的三次不同的绘制对象?
- for (int i=0;i<100;i++){
- int x = r.nextInt(width);
- int y = r.nextInt(height);
- g.drawOval(x,y,0,0);
- }
- //随机生成4位验证码
- String rn="";
- for(int i=0;i<4;i++){
- rn=code[r.nextInt(91)];
- g.setColor(new Color(20+r.nextInt(110),20+r.nextInt(110),20+r.nextInt(110)));
- g.drawString(rn,13*i+6,16);
- }
- g.dispose();//释放资源
- File file =new File("d://CodeImage.jpg");
- if(file.exists()){
- file.delete();
- try {
- file.createNewFile();
- ImageIO.write(pic, "jpg", file);
- System.out.println("验证码图片已创建!");
- } catch (Exception e) {
- e.printStackTrace();
- }}
- else{
- try {
- file.createNewFile();
- ImageIO.write(pic, "jpg", file);
- System.out.println("验证码图片已创建!");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String args[]){
- createimage();
- }
- }
复制代码 |