BufferedImage是Image的一个子类,BufferedImage生成的图片在内存里有一个图像缓冲区,利用这个缓冲区我们可以很方便的操作这个图片,通常用来做图片修改操作如大小变换、图片变灰、设置图片透明或不透明等。
通过BufferedImage来创建图片:
/**
* 创建图片
*/
public static void createImage(){
//设置字体样式
Font font = new Font("宋体", Font.PLAIN, 25);
//图片大小
int width = 1000;
int height = 1000;
//创建一个图片缓冲区
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//获取图片处理对象
Graphics graphics = image.getGraphics();
//填充背景色
graphics.setColor(getRandomColor());
graphics.fillRect(1, 1, width - 1, height - 1);
//设定边框颜色
graphics.setColor(getRandomColor());
graphics.drawRect(0, 0, width - 1, height - 1);
//设置干扰线
graphics.setColor(getRandomColor());
Random random = new Random();
for(int i=0;i<20;i++){
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int x1 = random.nextInt(width - 1);
int y1 = random.nextInt(height - 1);
graphics.drawLine(x, y, x1, y1);
}
//写入文字
graphics.setColor(getRandomColor());
graphics.setFont(font);
String content = new String("哈哈");
graphics.drawString(content, 100, 100);
//输出文件
File file = new File("E:\\123.gif");
try {
ImageIO.write(image, "GIF", file);
} catch (IOException e) {
e.printStackTrace();
}
//释放资源
graphics.dispose();
}
/**
* 获取随机颜色
* @return
*/
public static Color getRandomColor(){
Random random = new Random();
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
return new Color(r, g, b);
}
public static void main(String[] args){
createImage();
}
需要注意的:在通过drawString()写入中文时,需要设置字体,否则会出现乱码。
可以通过BufferedImage image = ImageIO.read(new FileInputStream(路径)); 对图片文件进行处理。