原图片正常,图片转成二进制字符串放入word文档中部分图片就显示不正常了,查询资料后发现,是因为使用java自带的工具类 ImageIo.read() 方法的问题,经过查阅得知ImageIo.read()方法读取图片时可能存在不正确处理图片ICC信息的问题,ICC为JPEG图片格式中的一种头部信息,导致渲染图片前景色时蒙上一层红色。
解决方法:
替换 ImageIo.read 方法
使用java 另一个工具类 Toolkit.getDefaultToolkit().getImage
Image src=Toolkit.getDefaultToolkit().getImage(file.getPath());
BufferedImage image=BufferedImageBuilder.toBufferedImage(src);//Image to BufferedImage
或者
Image imageTookit = Toolkit.getDefaultToolkit().createImage(bytes);
BufferedImage cutImage = BufferedImageBuilder.toBufferedImage(imageTookit);
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;
} 经测试后发现图片显示正常了
感谢这个博主的文章:点击打开链接
网上还有人说在linux 上安装其他软件解决此问题,后来想想太麻烦了,就没采用此方法。
Java使用ImageIo.read()方法从Word文档中读取图片时,可能出现图片显示红色的问题,原因是该方法可能不正确处理图片的ICC信息。解决方法是替换为 Toolkit.getDefaultToolkit().getImage。此外,还有在Linux上安装额外软件的解决方案,但因繁琐未采纳。

3183

被折叠的 条评论
为什么被折叠?



