能上代码就不说话:
public class ImageTest {
public static void main(String[] args) throws IOException {
int WIDTH = 100;
int HEIGHT = 36;
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Random random = new Random();
//取得画笔
Graphics2D graphics = bi.createGraphics();
// 绘制背景色
graphics.setColor(Color.white);
graphics.fillRect(0, 0, WIDTH, HEIGHT );
//绘制背景色结束
// 定义随机字符
char[] ch = "1234567890abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ"
.toCharArray();
int len = ch.length;
// 重新设置绘制字符的颜色
graphics.setColor(getRandomColor(100, 160, random));
for (int i = 0; i < 4; i++) {
int index = random.nextInt(len);
//设置字体
graphics.setFont(new Font("粗体", Font.BOLD + Font.ITALIC, 26));
//绘制字符串
graphics.drawString(ch[index] + "", i * 15 + 9, 30);
//绘制干扰线条
graphics.drawLine(random.nextInt(50), random.nextInt(50), random
.nextInt(80), random.nextInt(80));
}
graphics.dispose();
// 写出图片
FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\image.jpg");
ImageIO.write(bi, "JPG", fos);
fos.flush();
if(fos != null)
fos.close();
}
/*****
*
* @param littleColorNum 红绿蓝每种颜色RGB最小值
* @param largeColorNum 红绿蓝每种颜色RGB最大值
* @param random 随机数对象
* @return Color对象
*/
public static Color getRandomColor(int littleColorNum, int largeColorNum, Random random) {
if (littleColorNum > 255)
littleColorNum = 255;
if (largeColorNum > 255)
largeColorNum = 255;
int red = littleColorNum + random.nextInt(largeColorNum - littleColorNum);
int green = littleColorNum + random.nextInt(largeColorNum - littleColorNum);
int blue = littleColorNum + random.nextInt(largeColorNum - littleColorNum);
return new Color(red, green, blue);
}
}
效果图:
绘制过程和真实世界画画过程相似
1.先来张画布我才好挥毫泼墨啊
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
2.再来支画笔,无画笔岂不是巧妇难为无米之炊(JAVA语言买画布,赠送画笔)
//取得画笔
Graphics2D graphics = bi.createGraphics();
3.解决画布背景为黑问题(图片背景为黑问题),黑色不太漂亮,先用画笔沾点颜色,把整个画布涂上颜色,背景不就不为黑色了嘛,这里我涂成了白色
// 绘制背景色
graphics.setColor(Color.white);
graphics.fillRect(0, 0, WIDTH, HEIGHT );
注:这里绘制背景色的时候注意fillRect的几个参数,别设置错误,该往画布上涂,涂错了地方自然解决不了画布为黑问题,0,0表示画布左上角位置,WIDTH和HEIGTH表示涂的颜色宽和高的范围.
4.再沾点其他颜色,画4个字符串,其中加点其他干扰线条
// 定义随机字符
char[] ch = "1234567890abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ"
.toCharArray();
int len = ch.length;
// 重新设置绘制字符的颜色
graphics.setColor(getRandomColor(100, 160, random));
for (int i = 0; i < 4; i++) {
int index = random.nextInt(len);
//设置字体
graphics.setFont(new Font("粗体", Font.BOLD + Font.ITALIC, 26));
//绘制字符串
graphics.drawString(ch[index] + "", i * 15 + 9, 30);
//绘制干扰线条
graphics.drawLine(random.nextInt(50), random.nextInt(50), random
.nextInt(80), random.nextInt(80));
}
5.画完了,释放资源,把画布以文件流方式写出到硬盘里.(随机应变,哪里需要往那里写,做验证码的话当然是写到response.getOutputStream()输出流里了)
如有错误,欢迎指正
end