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

别来无恙 提交于 2019-12-07 03:48:12

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/14136475/what-is-the-difference-between-the-ways-to-read-an-image-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!