我有一个GIF图像并尝试将其读入BufferedImage。
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:
它与其他常规图像一起成功,但它与此图像失败。是图像问题还是API错误?
答案 0 :(得分:3)
这是知道JDK的bug见:
这些错误已在Java 9中修复。
答案 1 :(得分: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();
}
}
我希望我能帮助某人:)