我有很多 .ico 格式的图片,我想在我的 Java SE 项目中使用它们,但它不知道格式。我该如何解决这个问题?
3 回答
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"));
它也支持几种流行的元数据格式(EXIF、IPTC 和 XMP)。
TwelveMonkeys ImageIO允许扩展 ImageIO API 以支持 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);
此外,这里是我如何创建 Apache Commons Imaging 1.0-alpha2 无法读取的 .ico 文件的指南byte[]
(但可读取为File
且可读取为ByteArrayInputStream
):
- 启动 GIMP(在我的例子中是 2.10.22 版)
- 窗口菜单“文件”>“新建...”
- 模板:[空]
- 宽度:48 像素
- 高度:48px
- 其余部分保持原样(见下面的截图)
- 画一些东西(例如一个蓝点)
- 窗口菜单“文件”>“导出为...”
- 文件名:“bluedot.ico”
- 图标详细信息:“4 bpp,1 位 alpha,16 槽调色板”
- 压缩 (PNG):未选中
- 点击“导出”
Imaging.getAllBufferedImages(byte[])
会抛出org.apache.commons.imaging.ImageReadException: Can't parse this format.
Imaging.getAllBufferedImages(File)
将读取此文件。