emeraldhieu
emeraldhieu

Reputation: 9439

ImageIO.read() can't read some images

I have a GIF image and try to read it into 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);
    }

}

It shows errors:

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)

The "butterfly" image got from this open source project:

enter image description here

It succeeds with other regular images but it fails with this image. Is it image problem or API bug?

Upvotes: 4

Views: 3635

Answers (2)

M.Büßemeyer
M.Büßemeyer

Reputation: 53

I just found a solution for this problem presented on this page: http://web.archive.org/web/20200805050306/http://www.jguru.com/faq/view.jsp?EID=53328

Solution: By using the ImageIcon Class you can read a gif file and then draw it into a newly created BufferedImage.

The full code of the solution by http://web.archive.org/web/20200805050306/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();
  }
}

Upvotes: 2

Related Questions