imageio.read()无法读取某些图像

pod7payv  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(707)

我有一个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)

“蝴蝶”图片来自这个开源项目:

它在其他常规图像中成功,但在该图像中失败。是图像问题还是api错误?

mzmfm0qo

mzmfm0qo1#

这是了解jdk的错误,请参见:
对格式错误的png调用imageio.read()时发生indexoutofboundsexception异常
imageio.read()对某些错误的gif文件引发indexoutofboundsexception
jdk-6967419:绘制PNG时出现索引自动边界异常
这些错误在Java9中已修复。

whlutmcx

whlutmcx2#

我知道有点晚了,但我刚刚找到了解决此问题的方法,在本页中介绍:http://www.jguru.com/faq/view.jsp?eid=53328
解决方案:通过使用imageicon类,您可以读取gif文件,然后将其绘制到新创建的BuffereImage中。
解决方案的完整代码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();
  }
}

我希望我能帮助某人:)

相关问题