How do I load a GIF file into a BufferedImage?

John Zukowski

To load a GIF into a BufferedImage, load the Image normally, get its size, then create an empty BufferedImage of the appropriate size and draw the Image into the buffered image's Graphics context.

The following demonstrates this:


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);

    // 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();
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact