Displaying images in FLTK

Taking a picture from a file and displaying it in FLTK is a two-step process. First you read the file into an (invisible) image object, then you call the image() method of a visible widget with the image object as the argument. This enables you to use the same image many times, or change the displayed image, without re-reading the image file.

Using jpg image files is straightforward:

#include <FL.FL_Box.H>
#include <FL.FL_JPEG_Image.H>
..etc...
// A visible widget that will show the image
Fl_Box* mypicturebox;  
// You can also put images on buttons etc.

// This will be the invisible image object.
Fl_JPEG_Image* myimage;  
...etc...

int main() {
    ...etc...
    myimage = new Fl_JPEG_Image("nicepic.jpg"); // Reads the file you have put in
                                                // the same place as the code.
    ...etc...
    mypicturebox = new Fl_Box(20, 20, 100, 100); // Make it the right size, empty for now.
    ...etc...
    mypicturebox->image(myimage);    // Display or change the image whenever you like
    mypicturebox->redraw();          // (e.g. within a callback function)

Finally, it is necessary to tell the compiler to link in some library functions that handle the images. From the Quincy menu, select Tools|Options, and enter in the "Linker options" section -lfltk_images -lfltk_jpeg .

It is also possible to handle png images (the linker options in this case are -lfltk_images -lfltk_png -lfltk_z), and images that you construct from data in the program (see the Fl_Image documentation).

Here are the source code and image files (1, 2, 3) for a full example program. Don't forget to set the linker options.


MSC Nov 2005