Mirage2/src/core/widgets/image.py

87 lines
2.4 KiB
Python

# Python imports
# Lib imports
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import GdkPixbuf
try:
from PIL import Image as PImage
except Exception as e:
PImage = None
# Application imports
class Image(Gtk.EventBox):
def __init__(self, path = None):
super(Image, self).__init__()
self._thumbnail_with = settings.get_thumbnail_with()
self._thumbnail_height = settings.get_thumbnail_height()
self.is_loaded = False
self.image = None
self.path = path
self._setup_styling()
self._setup_signals()
self._load_widgets()
def _setup_styling(self):
...
def _setup_signals(self):
self.connect("button-release-event", self.set_image_to_view)
def _subscribe_to_events(self):
...
def _load_widgets(self):
self.image = Gtk.Image()
self.image.show()
self.add(self.image)
def set_image_to_view(self, widget = None, eve = None):
if eve.button == 1:
event_system.emit("handle_file_from_dnd", (self.path, ))
def load_pixbuf(self):
self.set_from_pixbuf( self.get_pixbuf_data(self.path, \
self._thumbnail_with, \
self._thumbnail_height) )
self.is_loaded = True
def set_from_pixbuf(self, pixbuf):
self.image.set_from_pixbuf(pixbuf)
def get_pixbuf_data(self, path, w = 126, h = 126):
path = self.path if not path else path
pixbuf = None
if PImage and path.endswith(".webp"):
return self.image2pixbuf(path, w, h)
try:
pixbuf = Gtk.Image.new_from_file(path).get_pixbuf()
except Exception:
pixbuf = Gtk.Image.new_from_resource(path).get_pixbuf()
return pixbuf.scale_simple(w, h, 2) # 2 = BILINEAR and is best by default
def image2pixbuf(self, path, _w, _h):
"""Convert Pillow image to GdkPixbuf"""
im = PImage.open(path)
data = im.tobytes()
data = GLib.Bytes.new(data)
w, h = im.size
pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(data, GdkPixbuf.Colorspace.RGB,
False, 8, w, h, w * 3)
return pixbuf.scale_simple(_w, _h, 2) # 2 = BILINEAR and is best by default