Images+Callbacks

Lesson 3: Images and Callbacks

Example code:

from fltk import *

pic = Fl_PNG_Image('cat.png')
ar = pic.w()/pic.h() #aspect ratio
bh = int(300/ar) #correct box height for width of 300

win = Fl_Window(300, bh, 'Cat Image')
win.begin()
box = Fl_Box(0, 0, 300, bh) #box has same aspect ratio as image
win.end()

pic = pic.copy(box.w(), box.h())  #resize image
box.image(pic)

win.show()
Fl.run()

Output:

cat_copy.png

High Quality resizing using the PIL imaging library and io library for in memory byte streams. Feel free to copy this function for your own use. It will accept any image format which PIL accepts and convert it to an Fl_PNG_Image. Also, note that replacing None with a name in the return line will create an Fl_Shared_Image which will be added to the list of shared images (see: Fl_Shared_Image) and will be available by that name.

from fltk import *
from PIL import Image
import io

def img_resize(fname,width):
    '''resizes any image type using high quality PIL library'''
    img = Image.open(fname) #opens all image formats supported by PIL
    w,h = img.size
    height = int(width*h/w)  #correct aspect ratio
    img = img.resize((width, height), Image.BICUBIC) #high quality resizing
    mem = io.BytesIO()  #byte stream memory object
    img.save(mem, format="PNG") #converts image type to PNG byte stream
    siz = mem.tell() #gets size of image in bytes without reading again
    return Fl_PNG_Image(None, mem.getbuffer(), siz)

pic = img_resize('cat.jpg', 300) #resizes to 300 pixels width
win = Fl_Window(pic.w(), pic.h(), 'PIL resizing')
win.begin()
box = Fl_Box(0, 0, pic.w(), pic.h())
win.end()

box.image(pic)

win.show()
Fl.run()

Output:

catjpg.png

Example Code:

from fltk import *

def but_cb(wid):
    wid.color(FL_GREEN)

LB=[]
win = Fl_Window(400,400)
win.begin()
for row in range(10):
    for col in range(10):
        LB.append( Fl_Button(col*40, row*40, 40, 40, str(len(LB))) )
        LB[-1].callback(but_cb)
win.end()

win.resizable(win) #window and all child widgets resize
win.show()
Fl.run()

Output: button_grid