Re: display/update a jpeg image?




On Dec 19, 2006, at 5:04 PM, Colin Anderson wrote:

I am trying to make a simple image viewer application. My script reads in the file names from a directory of .jpg images and uses these names to fill a List widget. I would like to display the first image in the list by default and have that image updated/ replaced every time another image is selected from the List widget. How do I go about doing this? Is there some sample code I could reference? I have done some searching in the tutorials and docs, but can only find very basic pixmap examples.
If your needs are simple, then Gtk2::Image does this nicely, as in the code below. Also illustrates how to convert filenames to and from unicode (i hope i did that right, works for me), respond to a tree selection, and make one side of a paned widget sticky. Please be gentle, i only spent about ten minutes on it.

If you need scaling or any sort of effects, you'll have work to do.


#!/usr/bin/perl -w
use strict;
use Gtk2 -init;
use Glib qw(TRUE FALSE);
use File::Spec;
use File::Basename;

my $directory = shift @ARGV || '.';

my $liststore = Gtk2::ListStore->new ('Glib::String');
foreach my $file (<$directory/*.jpg>) {
        $file = Glib::filename_to_unicode (basename $file);
        $liststore->set ($liststore->append, 0, $file);
}


my $window = Gtk2::Window->new;
$window->signal_connect (destroy => sub { Gtk2->main_quit });

my $hpaned = Gtk2::HPaned->new;

my $image = Gtk2::Image->new;


my $treeview = Gtk2::TreeView->new ($liststore);
$treeview->insert_column_with_attributes
        (-1, 'File name', Gtk2::CellRendererText->new, text => 0);

$treeview->get_selection->signal_connect (changed => sub {
        my $selection = shift;
        my ($model, $iter) = $selection->get_selected;
        my $file = $model->get ($iter, 0);
        $file = Glib::filename_from_unicode ($file);
        $file = File::Spec->catfile ($directory, $file);
        $image->set_from_file ($file);
});


$window->add ($hpaned);
$hpaned->pack1 (scrolled ($treeview, FALSE), FALSE, FALSE);
$hpaned->pack2 (scrolled ($image, TRUE), TRUE, TRUE);


$window->show_all;
Gtk2->main;

sub scrolled {
        my $widget = shift;
        my $use_viewport = shift;
        my $scroller = Gtk2::ScrolledWindow->new;
        $scroller->set_policy ('automatic', 'automatic');
        # There should be a way to figure out from perl whether this is
        # necessary, but i don't feel like poking at the docs that much. :-P
        if ($use_viewport) {
                $scroller->add_with_viewport ($widget);
        } else {
                $scroller->add ($widget);
        }
        return $scroller;
}






[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]