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;
}
(完)
文章抄自:sunqiqiqi