要扩展 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,但如果你仔细观察,你会发现一大堆蓝色阴影可以去掉对角线的锯齿状外观。