2016-03-28 1363 views
3

我有一個GIF圖像,並嘗試將其讀入BufferedImage。ImageIO.read()無法讀取一些圖像

public class ImageReadTest { 

    public static void main(String[] args) throws IOException { 
     f(new File("/Users/hieugioi/Downloads/Photos/butterfly.gif")); 
    } 

    public static void f(File file) throws IOException { 
     BufferedImage image = ImageIO.read(file); 
    } 

} 

它顯示錯誤:

Exception in thread "main" java.lang.IndexOutOfBoundsException 
    at java.io.RandomAccessFile.readBytes(Native Method) 
    at java.io.RandomAccessFile.read(RandomAccessFile.java:377) 
    at javax.imageio.stream.FileImageInputStream.read(FileImageInputStream.java:117) 
    at com.sun.imageio.plugins.gif.GIFImageReader.getCode(GIFImageReader.java:351) 
    at com.sun.imageio.plugins.gif.GIFImageReader.read(GIFImageReader.java:950) 
    at javax.imageio.ImageIO.read(ImageIO.java:1448) 
    at javax.imageio.ImageIO.read(ImageIO.java:1308) 
    at com.hieutest.ImageReadTest.f(ImageReadTest.java:16) 
    at com.hieutest.ImageReadTest.main(ImageReadTest.java:12) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:497) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) 

的 「蝴蝶」 的形象從this open source project有:

enter image description here

它成功與其它常規的圖像,但它不能與此圖像。它是圖像問題還是API錯誤?

+0

[ImageIO.read()拋出IndexOutOfBoundsException異常某些不良GIF文件(HTTPS: //bugs.openjdk.java.net/browse/JDK-6687967)...沒有幫助,但至少你並不孤單 – MadProgrammer

+1

我在Photoshop中打開文件並再次保存(作爲一個單獨的文件gif)並且它讀取文件。有一些關於特定圖像編碼的方式,Java不喜歡 – MadProgrammer

回答

3
+0

謝謝,但是這個錯誤是關於繪製圖像,而不是讀取。 「使用以下方法將PNG圖像繪製到ServletOutputStream中時使用以下方法:javax.imageio.ImageIO.write」 – Emerald214

+0

查看另一個有多個與此主題相關的錯誤。 –

+0

GIF錯誤似乎仍然處於OPEN/Unresolved狀態... :-(我真的很驚訝看到Java 9中修復的錯誤,這些錯誤已經打開很長一段時間了...... – haraldK

2

我知道這是一個有點後期,但我剛剛找到了解決此問題的解決方案:http://www.jguru.com/faq/view.jsp?EID=53328

解決方案: 通過使用的ImageIcon類,你可以讀一個GIF文件,然後將其拉入一個新創建的BufferedImage。

http://www.jguru.com/faq/view.jsp?EID=53328解決方案的全碼:

import java.awt.*; 
import java.awt.image.*; 
import javax.swing.*; 

public class BuffIt { 
public static void main (String args[]) { 
    // Get Image 
    ImageIcon icon = new ImageIcon(args[0]); 
    Image image = icon.getImage(); 

    // Create empty BufferedImage, sized to Image 
    BufferedImage buffImage = 
     new BufferedImage(
      image.getWidth(null), 
      image.getHeight(null), 
      BufferedImage.TYPE_INT_ARGB);//you can use any type 

    // Draw Image into BufferedImage 
    Graphics g = buffImage.getGraphics(); 
    g.drawImage(image, 0, 0, null); 

    // Show success 
    JFrame frame = new JFrame(); 
    JLabel label = new JLabel(new ImageIcon(buffImage)); 
    frame.getContentPane().add(label); 
    frame.pack(); 
    frame.show(); 
    } 
} 

我希望我能夠幫助別人:)