Next question: Example image code >>
There is code in the Java standard runtime library to do loading and saving, but the range of functionality depends heavily on the Java version that you are using. If you cannot assume any Java versions because your code is supposed to run even with older Java virtual machines, there is nothing but loading GIF and JPEG files.
In addition quite a few third-party libraries exist. I've assembled a list of libraries to read and write pixel and vector image files. If you find Java code to read or write images that is not linked on that page, please tell me!
Some additional hints for picking a library—trying each and every one of them seems to be a rather time-consuming task.
Avoid external libraries if you can. No need to add 3rd-party-code to your program if all you need is already in the standard runtime library.
java.awt.Toolkit has
createImage
methods which will do that for you (since Java 1.0).
You might want to use a MediaTracker to make sure an image is
loaded completely before continuing.
I have written a small demo program that
shows how to load images with Toolkit and MediaTracker.ImageIcon constructor
that takes a file name as argument and does all the rest.
Toolkit as well.
javax.imageio
hierarchy also lets you write PNG and JPEG.
This program demonstrates how to write a
BufferedImage to a PNG file with javax.imageio.ImageIO.
Note that there is a bug with JPEG writing in javax.imageio which has
been fixed since 1.4.1:
bug
4415068 in the bug parade (developer connection login required).
com.sun.image.codec.jpeg which lets you
read
and write JPEG files.
Here is a sample program for writing JPEG files with this package.Toolkit typically uses
native code for JPEG, PNG and GIF that is relatively fast.
At least one of the libraries in my list also uses native code - you'll probably get a speed-up, but you are no longer platform-independent.
If you have several choices for the file format you need, you may want to test if they are all sufficient when it comes to speed.
A note to readers who prefer German:
In der FAQ der deutschsprachigen Java-Newsgroup de.comp.lang.java
gibt es auch einen Abschnitt zum Thema
Laden und Speichern von Bildern
(alternativ: http://www.faqs.org/faqs/de/comp-lang-java/faq/).