What is the difference between the ways to read an Image file in Java?
Asked Answered
G

2

6

There are various ways of reading an image file in java such as BufferedImage and ImageIcon to name a few. I want to know what is the difference between these cases? Are they context dependent that in a particular case only one of them can be used?

What would be the best way of reading a image selected by JFileChooser by the user and separating the color channels of an image?

Gettings answered 3/1, 2013 at 9:54 Comment(1)
"reading Image file in java such as BufferedImage" The BufferedImage API offers no method for reading images. DYM javax.imageio.ImageIO, and java.awt.Toolkit?Womble
C
6

A good way is to use the different ImageIO.read methods, which return BufferedImage objects.

Image is an abstract class, so I think the real question is which subclass is more efficient for your program. Use VolatileImage if you need hardware acceleration. More on that here.

Candelabrum answered 3/1, 2013 at 9:57 Comment(2)
Agreed, ImageIO is the way to go (when not using JavaFX at least).Gravely
@Gimby: How would you do it when using JavaFX?Candelabrum
A
3

ImageIcon (and Toolkit#createImage/Toolkit#getImage) use a background loading process. That is, after you call these methods, they will return immediately, having created a background thread to actually load the image data.

These were/are used when loading large images across slow connections, like ye old 28k modems (ah, how I remember the days). This means that your application can continue running while the images are been downloaded.

You'll find in the Graphics class the drawImage methods accept an ImageObserver interface and that java.awt.Component implements this interface, this allows components the ability to automatically update themselves once the image has actually finished loading.

ImageIO on the other hand will not return until the image is fully loaded. It also makes it easier to introduce new readers/writers, making the API far more flexible then the original API. ImageIO also supports a wider range of images out of the box.

BufferedImage is also a far more flexible image class, especially when it comes to apply effects to the image.

Now, I, personally, prefer ImageIO. If I know I'm loading large images or images over a potentially slow connection, I will create my own background thread to load them. While a little more complicated, the trade offs greatly out weight the small amount of extra work -IMHO

What would be the best way of reading a image selected by JFileChooser by the user and separating the color channels of an image?

ImageIO without a doubt. In order to do any serious manipulation of an image loaded using something ImageIcon, you'd have to convert that image to a BufferedImage anyway

Alfonso answered 3/1, 2013 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.