BufferedImage处理图片及创建图片

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(路径)); 对图片文件进行处理。


  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值