如何在Java中读取ico格式的图片?

9

我有很多.ico格式的图片,想在我的Java SE项目中使用它们,但该项目不支持该格式。我该如何解决这个问题?


Java似乎不支持ico格式。请尝试使用此链接:https://dev59.com/VWgu5IYBdhLWcg3wxZtM - mindandmedia
3个回答

7

试用image4j - 适用于Java的图像库

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"));

4

Apache Commons Imaging 可以读写ICO文件:

    List<BufferedImage> images = Imaging.getAllBufferedImages(new File("input.ico"));

它还支持几种流行的元数据格式(EXIF、IPTC 和 XMP)。 TwelveMonkeys ImageIO 可以扩展 ImageIO API,以支持 ICO 和众多其他图像文件格式。

1
我有一些.ico文件,Apache Commons Imaging无法读取(它们也不是png文件)。而且过去没有太多的发布版本(根据https://mvnrepository.com/artifact/org.apache.commons/commons-imaging):2019年的1.0-alpha1,2020年的1.0-alpha2。截至目前(2021年9月),2021年没有任何发布版本。 - user14972917
@endofrainbow,就我个人而言,我更喜欢使用TwelveMonkeys,因为它没有依赖关系并且一直在积极维护。你知道哪些.ico文件无法使用Apache Commons Imaging读取吗?如果有必要,我建议你提交一个错误报告。 - gouessej
是的,我知道有问题的.ico文件(不会在这里发布,因为它们包含公司标志)。我将尝试使用TwelveMonkeys读取它们,然后报告。这需要一些时间,因为目前我对手动解决方法感到满意:(a)在GIMP中加载.ico文件(b)重新导出为.ico(c)使用Apache Commons Imaging读取。自动处理的.ico文件数量很少。 - user14972917

0

使用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[] 读取(但可以作为 FileByteArrayInputStream 读取):

  • 启动 GIMP(我的版本是 2.10.22)
  • 窗口菜单 "文件" > "新建..."
  • 模板:[空白]
  • 宽度:48px
  • 高度: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) 将读取此文件。

Dialog for creating an ico file


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接