我有很多.ico格式的图片,想在我的Java SE项目中使用它们,但该项目不支持该格式。我该如何解决这个问题?
image4j库允许您在100%纯Java中读取和写入某些图像格式。
目前支持以下格式:
- BMP(Microsoft位图格式 - 未压缩; 1、4、8、24和32位)
- ICO(Microsoft图标格式 - 1、4、8、24和32位 [XP未压缩,Vista压缩])
使用此库,您可以轻松解码ico文件
List<BufferedImage> image = ICODecoder.read(new File("input.ico"));
Apache Commons Imaging 可以读写ICO文件:
List<BufferedImage> images = Imaging.getAllBufferedImages(new File("input.ico"));
使用Apache Commons Imaging 1.0-alpha2读取ico文件的提示:
似乎在将ico文件作为文件和将ico文件作为byte[]读取之间存在差异:Imaging.getAllBufferedImages(File)
可以读取ico文件,Imaging.getAllBufferedImages(new ByteArrayInputStream(byte[] icoFileContent, yourIcoFilename)
也可以读取ico文件。Imaging.getAllBufferedImages(byte[])
无法读取相同的ico文件,而会抛出ImageReadException
异常。请参见下面的代码。
File icoFile = new File("bluedot.ico");
// Works fine
List<BufferedImage> images = Imaging.getAllBufferedImages(icoFile);
Assert.assertFalse(images.isEmpty());
ImageIO.write(images.get(0), "png", new File("bluedot.png"));
// Also works fine
byte[] icoFileContent = Files.readAllBytes(icoFile.toPath());
images = Imaging.getAllBufferedImages(new ByteArrayInputStream(icoFileContent), "bluedot.ico");
Assert.assertFalse(images.isEmpty());
ImageIO.write(images.get(0), "png", new File("bluedot2.png"));
// Throws an exception
images = Imaging.getAllBufferedImages(icoFileContent);
此外,这里有一个指南,介绍我如何创建一个不可读的 .ico 文件,Apache Commons Imaging 1.0-alpha2 无法将其作为 byte[]
读取(但可以作为 File
和 ByteArrayInputStream
读取):
Imaging.getAllBufferedImages(byte[])
将抛出 org.apache.commons.imaging.ImageReadException: Can't parse this format.
Imaging.getAllBufferedImages(File)
将读取此文件。