5

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

// 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 事物的回归吗?还是我只是愚蠢(我猜这是最后一个:))

4

2 回答 2

6

要扩展 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" );
}

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

于 2009-02-26T19:59:49.983 回答
3

http://java.sun.com/javase/6/docs/api/javax/imageio/package-summary.html#gif_plugin_notes

请注意,GIF 只能存储 256 种颜色。

于 2009-02-26T19:28:58.310 回答