java - ImageIO.write 不保存为 gif,但适用于 jpgs 和 pngs?

标签 java javax.imageio

我怀疑这里的解决方案可能真的很简单,但我很难过......

// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);

// fill image data (works fine)
ImageIO.write(bufferedImage, "JPG", f1); // works fine
ImageIO.write(bufferedImage, "PNG", f2); // works fine
ImageIO.write(bufferedImage, "GIF", f3); // this returns false, creates a broken gif file, but fires no exceptions

ImageIO.write() 不适用于 gif 吗?这是某种让 gif 成为专有 Compuserve 东西的倒退吗?还是我只是愚蠢(我猜这是最后一个 :))

最佳答案

扩展 Iny 的回答:

基本上,您应该做的不是另存为 gif。 GIF 是一个 256 色调色板图像(因此它的文件大小很小)。如果您的图像有超过 256 种颜色,您需要在尝试保存之前将颜色采样率降低到 256 种。编码器不会为你做这件事,因为它不知道该做什么。它可能会开始写入图像,一旦超过 256 色,就会退出。

我想你可以这样做(伪代码)

// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);

... //fill image data (works fine)

ImageIO.write(bufferedImage, "JPG", f1); // works fine

ImageIO.write(bufferedImage, "PNG", f2); //works fine

// downsample to lower color depth by using BYTE_RGB?
BufferedImage crappyImage = new BufferedImage(w,h,BufferedImage.TYPE_BYTE_RGB);
crappyImage.getGraphics().drawImage(bufferedImage, 0, 0, w, h, null);
// or you could repeat the drawing code above with less colors


if (!ImageIO.write(crappyImage , "GIF", f3))
{
   //still too many colors
   f3.delete();
   showError( "Could not save as gif, image had too many colors" );
}

如果您的绘图代码使用 Antialiasing 看起来不错,那会增加颜色深度而不用考虑它。例如,在白色背景上画一条 AA'd 对角线蓝线看起来是两种颜色,Color.WHITE 和 Color.BLUE,但如果你仔细观察,你会发现一大堆蓝色阴影可以去掉对角线的锯齿状外观。

关于java - ImageIO.write 不保存为 gif,但适用于 jpgs 和 pngs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/592032/

相关文章:

java - 查找二维数组中最接近的非零单元

html - 无效的 PNG 图像文件 : iDOT doesn't point to valid IDAT chunk

iphone - 图片IO : <ERROR> JPEG Corrupt JPEG data: premature end of data segment iphone - how to catch this?

java - java (android) 中的 ImageIO 类中的这个错误是什么?

ios - iOS 不会自动清除 ImageIO 脏内存

java - 有人使用 Eclipse/Maven 的 JRuby 测试框架吗?

java - Java BigInteger 中递归地添加数字

java - 已具有 try-catch 子句的方法的 Junit 测试用例

java - JPA/Hibernate : @ManyToOne and @OneToOne relationships tagged as FetchType. LAZY 和 optional = false 不在 em.find() 上延迟加载?

java - 需要帮助加载 ImageIO 插件读取器/写入器