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?
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.
ImageIcon
(andToolkit#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 thedrawImage
methods accept anImageObserver
interface and thatjava.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 -IMHOImageIO
without a doubt. In order to do any serious manipulation of an image loaded using somethingImageIcon
, you'd have to convert that image to aBufferedImage
anyway