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

编程入门 行业动态 更新时间:2024-10-25 22:25:10

java上传图片,压缩、更改尺寸等导致变色(<a href=https://www.elefans.com/category/dzcp/d7c0324cb07a242232465ce5027f88fa.html style=表层蒙上一层红色)"/>

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 loadedimage = 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 modelint type = BufferedImage.TYPE_INT_RGB;bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);}// Copy image to buffered imageGraphics g = bimage.createGraphics();// Paint the image onto the buffered imageg.drawImage(image, 0, 0, null);g.dispose();return bimage;}

 

 

 

 

 

 

更多推荐

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

本文发布于:2024-03-05 20:38:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1713356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表层   上传图片   尺寸   红色   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!