java上传图片,压缩、更改尺寸等导致变色(表层蒙上一层红色)

    做项目的时候遇到要对图片尺寸做处理,结果就会导致上传的图片会蒙上一层红色,代码如下

public void updateFileSize(String filePath) throws Exception {
		// 读取图片
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(filePath));
		// 字节流转图片对象
		Image bi = ImageIO.read(in);
		// 获取图像的高度,宽度
		int height = bi.getHeight(null);
		int width = bi.getWidth(null);

		int toHeight = GlobalConstant.BASE_FILE_SIZE_NORMAl;
		int toWidth = GlobalConstant.BASE_FILE_SIZE_NORMAl;

		if (toHeight != height && toWidth != width) {
			// 构建图片流
			BufferedImage tag = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
			// 绘制改变尺寸后的图
			tag.getGraphics().drawImage(bi, 0, 0, toWidth, toHeight, null);
			// 输出流
			String imageType = getFormatName(new File(filePath));
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filePath));
			ImageIO.write(tag, imageType, out);
			in.close();
			out.close();
		}
	}

原图

处理后的图

浪费了很多时间,换各种处理图片的方法都没找到问题,才发现只要使用ImageIO.read(in)读取图片可能就会导致变色。可通过BufferedImage读取图片,即可解决问题。代码如下:

 

Image src = Toolkit.getDefaultToolkit().getImage(filePath);
BufferedImage image = this.toBufferedImage(src);// Image to BufferedImage

 

public BufferedImage toBufferedImage(Image image) {
		if (image instanceof BufferedImage) {
			return (BufferedImage) image;
		}
		// This code ensures that all the pixels in the image are loaded
		image = new ImageIcon(image).getImage();
		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		try {
			int transparency = Transparency.OPAQUE;
			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
		} catch (HeadlessException e) {
			// The system does not have a screen
		}
		if (bimage == null) {
			// Create a buffered image using the default color model
			int type = BufferedImage.TYPE_INT_RGB;
			bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
		}
		// Copy image to buffered image
		Graphics g = bimage.createGraphics();
		// Paint the image onto the buffered image
		g.drawImage(image, 0, 0, null);
		g.dispose();
		return bimage;
	}

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值