I trying to use the library gdk for scale down an image and apply it to a GdkImage.
This is the codepixbuf = Gdk.pixbuf_new_from_file(fileName) pixbuf = pixbuf.scale_simple(100, 100, Gdk.INTERP_BILINEAR)
The problem is that python can't find Gdk even if I use everything in lowercase
Error: pixbuf = Gdk.pixbuf_new_from_file(fileName) NameError: global name 'Gdk' is not defined
I don't know what should I do because I tried to import Gdk but nothing is changed
2 Answers
Try importing it like this:
from gi.repository import Gtk from gi.repository.GdkPixbuf import Pixbuf, InterpTypethen:
pixbuf = Pixbuf.new_from_file(filename) pixbuf = pixbuf.scale_simple(100, 100, InterpType.BILINEAR)I would recommend using the command below because it automatically scales it when it reads it in. Just specify how big (pixels) you want the image to be:
pixbuf = Pixbuf.new_from_file_at_size(size_x, size_y, filename)- Using scale_simple() does not preserve aspect ratio.
- Using new_from_file_at_size() preserves aspect ratio
I had the same problem. Your answer almost worked for me, but I got the following errormessage:
AttributeError: 'gi.repository.Gdk' object has no attribute 'INTERP_BILINEAR'But I found the definition of it here gtkmm:gdkmm Enums and Flags:
Gdk::InterpType { Gdk::INTERP_NEAREST, Gdk::INTERP_TILES, Gdk::INTERP_BILINEAR, Gdk::INTERP_HYPER
}So for me it worked when I called the function like this:
from gi.repository import Gtk, Gdk
from gi.repository.GdkPixbuf import Pixbuf
...
pixbuf = Pixbuf.new_from_file('mypic.gif')
pixbuf = pixbuf.scale_simple(desired_width, desired_height, 2) # 2 := BILINEAR...maybe this helps someone with the same problem ;)
1