101. How to get image size?

Problem

You have set up a simple drag-and-drop image viewer in How to create a simple drag and drop image viewer?

Now you would like to get the image size (e.g. maybe for further processing of the image, such as shrinking, rotating, image enhancement, etc.) as shown below:

How to get image size?


Solution


Sample Code

1   
2   
3   
4   
10   
11   
14   
15   
18   
24   
27   
30   
31   
32   
33   
34   
37   
39   
41   
42   
47   
48   
49   
50   
51   
52   
55   
60   
61   
62   
<?php
$window = new GtkWindow();
$window->set_size_request(100, 100);
$window->connect_simple('destroy', array('Gtk','main_quit'));

$img = new GtkImage();
$img->drag_dest_set(Gtk::DEST_DEFAULT_ALL,
    array( array( 'text/uri-list', 0, 0)), Gdk::ACTION_COPY);
$img->connect('drag-data-received', 'on_drop', $img);

$window->add($img);
$window->show_all();
Gtk::main();

// process drop
function on_drop($widget, $context, $x, $y, $data, $info, $time, $img) {
    $uri_list = explode("\n",$data->data);
    $img_file = $uri_list[0];
    $img_file2 = str_replace("file:///", "", $img_file);
    $img_file2 = str_replace("\r", "", $img_file2);
    $pixbuf=GdkPixbuf::new_from_file($img_file2);  // note 1
    $width = $pixbuf->get_width(); // note 2
    $height = $pixbuf->get_height(); // note 2
    $img->set_from_pixbuf($pixbuf); // note 3
    echo "image size = $width x $height\n";
    global $window;
    $window->set_size_request($width, $height); // note 4
}

?>

Output

As shown above.
 

Explanation

  1. Load the image into a pixbuf.
  2. Get the image width and height from the pixbuf.
  3. Display the image using the pixbuf.
  4. Resize the window based on the new image size.

Note

Note that the window will only auto-expand, but will not auto-shrink. php-gtk1 used to have a method GtkWindow::set_policy() that supports auto-shrink. But this is no longer available in php-gtk2. Until they add this back, there is no easy one-liner that allows you to auto-shrink based on image size.

Related Links

Add comment


Security code
Refresh