项目中有导出excel的功能,excel中包含图片,以前作的时候有些图片被蒙上了一层红色(当时发现内存大一点的图片会被蒙上红色,因此错误的觉得这是图片大小的问题,想从压缩图片大小的方向上去解决)java
最近项目准备上线了,这个问题又被抛出来了,经查阅资料发现,原来是在图片加载的时候出了问题 , 以前的代码: // 读取本地图片,指定图片类型为jpg
public void setPicture(HSSFWorkbook wb, HSSFPatriarch patriarch, String pic, int iRowStart, int iColStart, int iRowStop, int iColStop) throws IOException {
// 判断文件是否存在
File imgFile = new File(pic);
if (imgFile.exists()) {
// 图片处理
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
BufferedImage bufferImg = ImageIO.read(imgFile);
ImageIO.write(bufferImg, "jpg", byteArrayOut);
// 左,上(0-255),右(0-1023),下
HSSFClientAnchor anchor = new HSSFClientAnchor(20, 1, 1018, 0, (short) (iColStart), iRowStart, (short) (iColStop), iRowStop);
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
}
}less
这是导出excel中,读取本地图片并指定图片格式为jpg的代码,后来查阅资料发现ImageIO.read(imgFile)方法读取图片时可能存在不正确处理图片ICC信息的问题,ICC为JPEG图片格式中的一种头部信息,致使渲染图片前景色时蒙上一层红色。ui
解决方案:spa
使用JDK中提供的Image src=Toolkit.getDefaultToolkit().getImage 将BufferedImage bufferImg = ImageIO.read(imgFile);改成 excel
Image src=Toolkit.getDefaultToolkit().getImage(imgFile.getPath());
BufferedImage bufferImg=BufferedImageBuilder.toBufferedImage(src);//我用的就是这方法,亲测可行,网上还有另外一种方法code
另附上BufferedImageBuilder源码(直接从网上copy的,感谢大神):图片
public class BufferedImageBuilder {
public static 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;
}
}内存
至此,java处理图片时蒙上红色的问题已经解决!!!图片处理