title: Java: Reading images and displaying as an ImageIcon
body: <p>I'm writing an application which reads and displays images as ImageIcons (within a JLabel), the application needs to be able to support jpegs and bitmaps. </p>
  
  <p>For jpegs I find that passing the filename directly to the ImageIcon constructor works fine (even for displaying two large jpegs), however if I use ImageIO.read to get the image and then pass the image to the ImageIcon constructor, I get an OutOfMemoryError( Java Heap Space ) when the second image is read (using the same images as before).</p>
  
  <p>For bitmaps, if I try to read by passing the filename to ImageIcon, nothing is displayed, however by reading the image with ImageIO.read and then using this image in the ImageIcon constructor works fine.</p>
  
  <p>I understand from reading other forum posts that the reason that the two methods don't work the same for the different formats is down to java's compatability issues with bitmaps, however is there a way around my problem so that I can use the same method for both bitmaps and jpegs without an OutOfMemoryError?</p>
  
  <p>(I would like to avoid having to increase the heap size if possible!)</p>
  
  <p>The OutOfMemoryError is triggered by this line: </p>
  
  <pre><code>img = getFileContentsAsImage(file); 
  </code></pre>
  
  <p>and the method definition is: </p>
  
  <pre><code>public static BufferedImage getFileContentsAsImage(File file) throws FileNotFoundException { 
    BufferedImage img = null; 
    try { 
      ImageIO.setUseCache(false); 
      img = ImageIO.read(file); 
      img.flush(); 
    } catch (IOException ex) { 
      //log error 
    } 
  return img; 
  }
  </code></pre>
  
  <p>The stack trace is:</p>
  
  <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
          at java.awt.image.DataBufferByte.&lt;init&gt;(DataBufferByte.java:58)
          at java.awt.image.ComponentSampleModel.createDataBuffer(ComponentSampleModel.java:397)
          at java.awt.image.Raster.createWritableRaster(Raster.java:938)
          at javax.imageio.ImageTypeSpecifier.createBufferedImage(ImageTypeSpecifier.java:1056)
          at javax.imageio.ImageReader.getDestination(ImageReader.java:2879)
          at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:925)
          at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:897)
          at javax.imageio.ImageIO.read(ImageIO.java:1422)
          at javax.imageio.ImageIO.read(ImageIO.java:1282)
          at framework.FileUtils.getFileContentsAsImage(FileUtils.java:33)
  </code></pre>