6.3.7.6 Display an Image for the Selected Faculty Member in Canvas
There are different ways to store and display images in a database-related project. One professional way is to store all images as binary files in a database with all queried data together. As we did in Chapter 2 when we built our sample database, CSE _ DEPT, all faculty images have been stored in the fimage column as a sequence of binary data in our sample database, in the Faculty Table.
Unlike Visual Studio. NET, in environments such as Visual Basic.NET and Visual C#.NET, there is no PictureBox class available in Java to display an image or a picture. One needs to use a Canvas object as an image holder, a Graphics object as a tool to display an image and a MediaTracker class as a monitor to coordinate image processing.
In Java, the main package containing the key image processing classes, such as Image, Toolkit, Graphics and MediaTracker, is java.awt. Currently, the Java graphics programming library (AWT) supports GIF and JPEG images. Format considerations include local color palettes, feature restrictions (compression, color depth and interlacing, for example) and dithering.
We divide this section into the following three parts to make image displaying in Java more illustrative and straightforward:
1) Show the operational sequence to display an image in Java.
2) Create a user-defined method, ShowFaculty(), to select and display a desired faculty image.
3) Develop the additional code to coordinate this image display.
Now let’s start with the first part.
6.3.7.6.1 Operational Sequence to Display an Image in Java Usually, to display an image in Java, two steps should be performed:
1) Load an image from an image file.
2) Display that image by drawing it in a Graphics context.
For example, to load an image named “faculty.jpg”, use the getImage() method that belongs to the Toolkit class, which looks like:
Image img = myWindow.getToolkit().getImage(“faculty.jpg”);
where MyWindow is a Java GUI container, such as a JFrame, JDialog or JWindow, in which the image will be displayed. The getToolkit() method that belongs to the Java GUI container is used to get the Toolkit object. One point to be noted when this instruction is executed is that both the Image and Toolkit classes are abstract classes, which means that you cannot directly create new instances by invoking those classes’ constructors. Instead, you have to use methods related to those abstract classes.
After an image is loaded, display the image by drawing it in a Graphics context using
g.drawImage(img, x, y, width, height, imageObserver); where the object g is an instance of the Graphics class.