Why does ImageReader return incorrect BufferedImage?

前端 未结 2 1964
星月不相逢
星月不相逢 2020-12-11 18:23

I\'m trying to access a animated GIF image with 21 frames and then read the 12th (cause it starts at 0?) frame.

import java.awt.image.BufferedImage;
import j         


        
2条回答
  •  情深已故
    2020-12-11 19:23

    Code 1

    import java.net.URL;
    import java.awt.Image;
    import javax.imageio.ImageIO;
    
    class GetGifSize {
    
        public static void main(String[] args) throws Exception {
            URL urlToImage = new URL("http://i55.tinypic.com/263veb9.gif");
            Image image = ImageIO.read(urlToImage);
            System.out.println( "Image size is " +
                image.getWidth(null) +
                "x" +
                image.getHeight(null) );
        }
    }
    

    Output

    Image size is 200x220
    

    Code 2

    A variant of the code posted by trashgod.

    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    
    public class GifBounds {
    
        /** @see http://stackoverflow.com/questions/5688104 */
        public static void main(String[] args) throws IOException {
            search(new URL("http://i55.tinypic.com/263veb9.gif"));
        }
        public static void search(URL url) throws IOException {
            ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
            reader.setInput(ImageIO.createImageInputStream(url.openStream()));
            int i = reader.getMinIndex();
            int offset = i-0;
            int count = reader.getNumImages(true);
            System.out.println("Image count: " + count);
            for (int ii=i; ii<(count-i); ii++) {
                BufferedImage bi = reader.read(ii);
                System.out.println(ii
                    + offset
                    + ": " + bi.getWidth()
                    + ", " + bi.getHeight());
            }
        }
    }
    

    As an aside, I think you should mark trashgod's answer correct of the two answers.

    It was first to get to the real core of the problem. And you gotta' love an answer with screen-shots. That's going 'the whole 9 yards'.

提交回复
热议问题