我希望你們能幫助我解決這個問題。我不確定它是否是Java中的錯誤,或者我做錯了什麼,但是我會選擇後者。Java ImageWriter BufferedImage to GIF
我想將一個BufferedImage變成一個GIF圖像。然後我希望以字節數組的形式將GIF保存在內存中。 (我不想將文件保存到磁盤)
程序應該捕獲一個屏幕段(只是爲了創建一個快速圖像),並使用ImageIO ImageWriter和ByteArrayOutputStream將其轉換爲GIF字節數組。
下面的代碼會顯示錯誤。該程序將崩潰併發出ArrayIndexOutOfBoundsException,並且該數組保持爲空。如果你將「gif」替換爲「png」,它就可以正常工作,因此我很困惑。也!如果我將圖像保存到磁盤上的文件中
write.setOutput(ImageIO.createImageOutputStream(new FileOutputStream(new File("C:/Image.gif")));
它會將其正確保存到.gif文件中。
所以我的問題是,我在這段代碼中做了什麼錯誤?任何幫助將不勝感激! :)
注意:這不是一個動畫GIF,也不涉及任何透明度。
String format = "gif";
Robot r = null;
try {
r = new Robot();
} catch (AWTException e1) {
e1.printStackTrace();
}
BufferedImage screen = r.createScreenCapture(new Rectangle(512,512));
final BufferedImage gif = new BufferedImage(512,512,BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g = gif.createGraphics();
g.drawImage(screen,0,0,null);
g.dispose();
ImageWriter write = ImageIO.getImageWritersBySuffix(format).next();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
write.setOutput(ImageIO.createImageOutputStream(out));
write.write(gif);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for(int i=0; i < 10; i++) {
System.out.println(out.toByteArray()[i]);
}
哇,這很奇怪... – leonbloy
爲了更好地幫助,請發佈[SSCCE](http://sscce.org/)。 –