我怀疑这里的解决方案可能很简单,但我很难过......
// 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对角蓝线似乎是2种颜色,Color.WHITE和Color.BLUE,但如果你仔细观察,你会有一大堆蓝色阴影来摆脱对角线的锯齿状外观.