def __activate_set_data_cb(self, column, cell, model, tree_iter, data): # DOUBT: Currently I'm showing the a green icon when the font is active # and a red icon when its deactivated so I'm using the this cell as a # status indicator rather than a button with when shows a green tick # sign means the cell will be activated if the button is clicked - # is this setting correct? # FIXME: add tooltips here to that the user what icons mean what is_activated = model[tree_iter][ListModel.COLUMN_ACTIVATE] if is_activated == 1: loader = GdkPixbuf.PixbufLoader() loader.write(localIcon.activate.encode()) loader.close() cell.props.pixbuf = loader.get_pixbuf() elif is_activated == 0: loader = GdkPixbuf.PixbufLoader() loader.write(localIcon.deactivate.encode()) loader.close() cell.props.pixbuf = loader.get_pixbuf() else: loader = GdkPixbuf.PixbufLoader() loader.write(localIcon.lock.encode()) loader.close() cell.props.pixbuf = loader.get_pixbuf()
def __favorite_set_data_cb(self, column, cell, model, tree_iter, data): font_name = model[tree_iter][ListModel.COLUMN_FONT_NAME] favorite = font_name in fav_fonts if favorite: loader = GdkPixbuf.PixbufLoader() loader.write(svg_active.encode()) loader.close() cell.props.pixbuf = loader.get_pixbuf() else: loader = GdkPixbuf.PixbufLoader() loader.write(svg_inactive.encode()) loader.close() cell.props.pixbuf = loader.get_pixbuf()
def pixbuf_from_data(data, size=None, keep_ratio=True, upscale=False): """ Generates a pixbuf from arbitrary image data :param data: The raw image data :type data: byte :param size: Size to scale to; if not specified, the image will render to its native size :type size: tuple of int :param keep_ratio: Whether to keep the original image ratio on resizing operations :type keep_ratio: bool :param upscale: Whether to upscale if the requested size exceeds the native size :type upscale: bool :returns: the generated pixbuf :rtype: :class:`GdkPixbuf.Pixbuf` or None """ if not data: return None pixbuf = None loader = GdkPixbuf.PixbufLoader() if size is not None: def on_size_prepared(loader, width, height): """ Keeps the ratio if requested """ if keep_ratio: scale = min(size[0] / float(width), size[1] / float(height)) if scale > 1.0 and upscale: width = int(width * scale) height = int(height * scale) elif scale <= 1.0: width = int(width * scale) height = int(height * scale) else: if upscale: width, height = size else: width = height = max(width, height) loader.set_size(width, height) loader.connect('size-prepared', on_size_prepared) try: loader.write(data) loader.close() except GLib.GError as e: logger.warning( 'Failed to get pixbuf from data: {error}'.format(error=e.message)) else: pixbuf = loader.get_pixbuf() return pixbuf
def show(self): # Only load the pictures if it hasn't already. Ie.: the number of pics in metadata is different from those loaded. if not hasattr(self.raw_meta, 'pictures'): return False if len(self.raw_meta.pictures) != len(self.meta["pics"]): art_type = [ "Other", "File Icon", "Alternate File Icon", "Front Cover", "Back Cover", "Leaflet Page", "Media Label", "Lead Author", "Author", "Conductor", "Band", "Composer", "Lyrics Writer", "Recording Location", "During Perfomance", "Screen Capture", "Fish", "Band Logo", "Publisher Logo" ] if len(self.raw_meta.pictures) >= 1: for each in self.raw_meta.pictures: pixloader = gpix.PixbufLoader() pixloader.write(each.data) pixloader.close() self.meta["pics"][art_type[ each.type]] = pixloader.get_pixbuf() if each.type in (3, 2, 1) or self.meta["thumbnail"] == None: self.meta["thumbnail"] = pixloader.get_pixbuf( ).scale_simple(30, 30, gpix.InterpType.BILINEAR)
def get_pixbuf_from_buffer(self, image_buffer): """Buffer To Pixbuf""" pixbuf_loader = GdkPixbuf.PixbufLoader() pixbuf_loader.write(image_buffer) pixbuf_loader.close() pixbuf = pixbuf_loader.get_pixbuf() return pixbuf
def _data2pixbuf(data, width=None, height=None): loader = GdkPixbuf.PixbufLoader() if width and height: loader.set_size(width, height) loader.write(data) loader.close() return loader.get_pixbuf()
def __init__(self): Gtk.Window.__init__(self, title="CellRendererPixbuf Example") self.set_default_size(200, 200) self.liststore = Gtk.ListStore(str, str) self.liststore.append(["New", "document-new"]) self.liststore.append(["Open", "document-open"]) self.liststore.append(["Save", "document-save"]) treeview = Gtk.TreeView(model=self.liststore) renderer_text = Gtk.CellRendererText() column_text = Gtk.TreeViewColumn("Text", renderer_text, text=0) treeview.append_column(column_text) renderer_pixbuf = Gtk.CellRendererPixbuf() loader = GdkPixbuf.PixbufLoader() loader.write(svg.encode()) loader.close() renderer_pixbuf.props.pixbuf = loader.get_pixbuf() column_pixbuf = Gtk.TreeViewColumn("Image", renderer_pixbuf) treeview.append_column(column_pixbuf) self.add(treeview)
def load_from_stream(fp, progress=None): """Load a pixbuf from an open file-like object :param fp: file-like object opened for reading :param progress: Provides UI feedback. Must be sized (expected bytes). :type progress: lib.feedback.Progress or None :rtype: GdkPixbuf.Pixbuf :returns: the loaded pixbuf >>> with open("pixmaps/mypaint_logo.png", "rb") as fp: ... p = load_from_stream(fp) >>> isinstance(p, GdkPixbuf.Pixbuf) True If a progress feedback object is specified, its `items` field must have been pre-filled with the number of bytes expected before fp.read() returns an empty string. """ if progress and (progress.items is None): raise ValueError("progress argument must be sized if specified") loader = GdkPixbuf.PixbufLoader() while True: buf = fp.read(LOAD_CHUNK_SIZE) if buf == '': break loader.write(buf) if progress is not None: progress += len(buf) loader.close() return loader.get_pixbuf()
def get_pixbuf_from_data(file_data): """ Get image data and returns GdkPixbuf.Pixbuf """ pixbufloader = GdkPixbuf.PixbufLoader() try: pixbufloader.write(file_data) pixbufloader.close() pixbuf = pixbufloader.get_pixbuf() except GLib.GError: pixbufloader.close() log.warning('loading avatar using pixbufloader failed, trying to ' 'convert avatar image using pillow') try: avatar = Image.open(BytesIO(file_data)).convert("RGBA") array = GLib.Bytes.new(avatar.tobytes()) width, height = avatar.size pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(array, GdkPixbuf.Colorspace.RGB, True, 8, width, height, width * 4) except Exception: log.warning( 'Could not use pillow to convert avatar image, ' 'image cannot be displayed', exc_info=True) return return pixbuf
def __init__(self, push, pushbullet): self.pushbullet = pushbullet self.notification = Notify.Notification.new(push["title"], push["body"]) self.notification_id = push["notification_id"] self.package_name = push["package_name"] self.source_user_iden = push["source_user_iden"] if "notification_tag" in push: self.notification_tag = push["notification_tag"] else: self.notification_tag = None if push["icon"] is not None: pbl = GdkPixbuf.PixbufLoader() pbl.write(bytes(b64decode(push["icon"]))) pbl.close() self.notification.set_icon_from_pixbuf(pbl.get_pixbuf()) if push["dismissible"] == True: self.__dismiss_cb_id = self.notification.connect_after("closed", self.__dismiss_cb) self.notification.set_timeout(0) self.notification.set_urgency(Notify.Urgency.LOW) self.notification.show()
def run(self): try: response = requests.get(self.url) if response.status_code == 200: loader = GdkPixbuf.PixbufLoader() loader.write(response.content) loader.close() pixbuf = loader.get_pixbuf() height = pixbuf.get_height() * self.scale / 100.0 width = pixbuf.get_width() * self.scale / 100.0 scaled_buf = pixbuf.scale_simple( width, height, GdkPixbuf.InterpType.BILINEAR) if scaled_buf: surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, scaled_buf.get_width(), scaled_buf.get_height()) context = cairo.Context(surface) Gdk.cairo_set_source_pixbuf(context, scaled_buf, 0, 0) context.paint() self.emit('downloaded', True, surface, width, height) return except Exception as e: print(e) self.emit('downloaded', False, None, -1, -1) return
def get_pixbuf(self, image, shape="cover"): """get_pixbuf _ dosya yolu , maske PIL ile maske ile yeni bir pixbuf gönder""" iconPath = image highlight = Image.open('simgeler/%s.png' % shape) mask = Image.open('simgeler/%s-mask.png' % shape) icon = Image.open(iconPath).convert('RGBA') #.rotate(-6) button = Image.new('RGBA', mask.size) icon = ImageOps.fit(icon, highlight.size, method=Image.ANTIALIAS, centering=(0.5, 0)) helper = button.copy() helper.paste(icon, mask=mask) button.paste((255, 255, 255), mask=mask) icon = icon.convert('RGB') button.paste(icon, mask=helper) overlay = highlight.copy().convert('RGB') button.paste(overlay, mask=highlight) file1 = StringIO.StringIO() button.save(file1, "png") contents = file1.getvalue() file1.close() loader = gdkpixbuf.PixbufLoader() loader.set_size(80, 80) loader.write(contents) pixbuf = loader.get_pixbuf() loader.close() return pixbuf
def set_package_info(self, name, summary, tags, icon_url): """ Set the package information into the GUI. """ self.pkgname = name image = self.builder.get_object('image_pkg') try: response = urllib2.urlopen(icon_url) except: response = urllib2.urlopen('https://apps.fedoraproject.org/' 'packages/images/icons/' 'package_128x128.png') loader = GdkPixbuf.PixbufLoader() loader.write(response.read()) image.set_from_pixbuf(loader.get_pixbuf()) loader.close() label = self.builder.get_object('label_pkg') label.set_text('<b>%s</b>\n%s' % (name, summary or '')) label.set_use_markup(True) treeview = self.builder.get_object('treeview1') liststore = Gtk.ListStore(str) for tag in tags: liststore.append([tag]) treeview.set_model(liststore)
def specDone(self, fd, x): with os.fdopen(fd, "rb") as spec: loader = GdkPixbuf.PixbufLoader() loader.write(spec.read()) loader.close() self.spec_image.set_from_pixbuf(loader.get_pixbuf()) self.spec_image.show()
def create_preview(self, object_id): jobject = datastore.get(object_id) if 'preview' in jobject.metadata: preview = jobject.metadata['preview'] if preview is None or preview == '' or preview == 'None': if jobject.metadata['mime_type'] .startswith('image/') and \ jobject.metadata['mime_type'] != 'image/vnd.djvu': filename = jobject.get_file_path() self.show_image(filename) return if jobject.metadata['mime_type'] == 'application/x-cbz': filename = jobject.get_file_path() fname = self.extract_image(filename) self.show_image(fname) os.remove(fname) return self.show_image('xoimage.jpg') return if 'preview' in jobject.metadata and \ len(jobject.metadata['preview']) > 4: preview_data = jobject.metadata['preview'] loader = GdkPixbuf.PixbufLoader() loader.write(preview_data) scaled_buf = loader.get_pixbuf() loader.close() self.image.set_from_pixbuf(scaled_buf) self.image.show() else: self.image.clear() self.image.show()
def test(format_, data, gdi=False, skip_filename_load=False): print(format_) loader = GdkPixbuf.PixbufLoader() loader.write(data) loader.close() assert loader.get_format().get_name() == format_ assert loader.get_pixbuf() # this is the only place I found where the gdi info leaks in the api assert ("Gdip" in loader.get_animation().__gtype__.name) == gdi if not skip_filename_load: # add some unicode to test if filenames are handled properly fd, fn = tempfile.mkstemp(suffix="😃ÿ") os.close(fd) try: with open(fn, "wb") as h: h.write(data) f, w, h = GdkPixbuf.Pixbuf.get_file_info(fn) assert f.get_name() == format_ pb = GdkPixbuf.Pixbuf.new_from_file(fn) assert pb finally: os.remove(fn) formats_tested.append(format_)
async def update_thumbnail(filepath): self.widgets.image_preview.set_opacity(0.5) try: pbl = GdkPixbuf.PixbufLoader() try: async with self.open_thumbnail_image_of(filepath) as f: while True: data = await f.read(65536) if len(data) == 0: break pbl.write(data) finally: pbl.close() pixbuf = pbl.get_pixbuf() except Exception as e: self.widgets.image_preview.set_from_icon_name("gtk-missing-image", Gtk.IconSize.DIALOG) else: allocation = self.widgets.image_preview.get_parent().get_allocation() allocation_ratio = allocation.height/allocation.width image_ratio = pixbuf.props.height/pixbuf.props.width if image_ratio < allocation_ratio: new_width = allocation.width new_height = int(new_width * image_ratio) else: new_height = allocation.height new_width = int(new_height / image_ratio) pixbuf = pixbuf.scale_simple(new_width, new_height, GdkPixbuf.InterpType.BILINEAR) self.widgets.image_preview.set_from_pixbuf(pixbuf) self.widgets.image_preview.set_opacity(1)
def get_thumbnail_from_file(fileobj, boundary): """Like get_thumbnail() but works with files that can't be reopened. This is needed on Windows where NamedTemporaryFile can't be reopened. Can raise GLib.GError or return None. """ assert fileobj try: return get_thumbnail(fileobj.name, boundary) except GLib.GError: try: loader = GdkPixbuf.PixbufLoader() loader.write(fileobj.read()) loader.close() fileobj.seek(0, 0) # can return None in case of partial data pixbuf = loader.get_pixbuf() except EnvironmentError: pass else: if pixbuf is not None: return scale(pixbuf, boundary)
def get_image_pixbuf(self, image=None): url = self.get_image_url(image) r = requests.get(url) loader = GdkPixbuf.PixbufLoader() loader.write(r.content) loader.close() return loader.get_pixbuf()
def asyncload(): loader = GdkPixbuf.PixbufLoader() #these need to be stored separate from the self versions to prevent race conditions in cache path, name, buff = loadWithProgress(url, loadbar) (self.path, self.name) = (path, name) loader.write(buff) loader.close() #self.name=source.info().get_filename() #print("got filename: ", self.name) self.buf = loader.get_animation() self.iter = self.buf.get_iter() def finish(): self.media.set_from_animation(self.buf) self.progressbox.remove(loadbar) self.enableDrag() self.generateDrag() return False GObject.idle_add(finish) #flush to disk in background with open(path, 'wb+') as f: f.write(buff) imgcache[url] = path
def bytes2pixbuf(data, width=icon_size['width'], height=icon_size['height'], display_name=None): """ converts raw bytes into a GTK PixBug args: data (bytes): raw bytes width (int): width of image height (int): height of images returns: GtkPixbuf: a GTK Pixbuf """ loader = GdkPixbuf.PixbufLoader() loader.set_size(width, height) try: loader.write(data) loader.close() except GLib.Error as e: logger.error("can't process icon for {}: {}".format( display_name, str(e))) else: return loader.get_pixbuf()
def svg_str_to_pixbuf(svg_string): """ Load pixbuf from SVG string """ pl = GdkPixbuf.PixbufLoader('svg') pl.write(svg_string) pl.close() pixbuf = pl.get_pixbuf() return pixbuf
def cairo_surface_to_pixbuf(s): """ Converts a Cairo surface to a Gtk Pixbuf by encoding it as PNG and using the PixbufLoader. """ bio = io.BytesIO() try: s.write_to_png(bio) except: # Write an empty PNG file to the StringIO, so # in case of an error we have "something" to # load. This happens in PyCairo < 1.1.6, see: # http://webcvs.cairographics.org/pycairo/NEWS?view=markup # Thanks to Chris Arnold for reporting this bug bio.write('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4' 'c6QAAAAZiS0dEAP8A\n/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAA' 'AAd0SU1FB9cMEQkqIyxn3RkAAAAZdEVYdENv\nbW1lbnQAQ3JlYXRlZCB3a' 'XRoIEdJTVBXgQ4XAAAADUlEQVQI12NgYGBgAAAABQABXvMqOgAAAABJ\nRU' '5ErkJggg==\n'.decode('base64')) pbl = GdkPixbuf.PixbufLoader() pbl.write(bio.getvalue()) pbl.close() pixbuf = pbl.get_pixbuf() return pixbuf
def get_pixbuf_from_string(str): pbl = GdkPixbuf.PixbufLoader() data = base64.b64decode(str) pbl.write(data) pbl.close() return pbl.get_pixbuf()
def get_album_art(url, tmpdir, *extra): try: with urllib.request.urlopen(url) as f: image = f.read() except urllib.error.HTTPError: logging.warning('Invalid image url received') return ( None, None, ) + extra file_url = None if tmpdir: try: with tempfile.NamedTemporaryFile(prefix='art-', dir=tmpdir.name, delete=False) as f: f.write(image) file_url = urllib.parse.urljoin( 'file://', urllib.parse.quote(f.name)) except IOError: logging.warning("Failed to write art tempfile") with contextlib.closing(GdkPixbuf.PixbufLoader()) as loader: loader.set_size(ALBUM_ART_SIZE, ALBUM_ART_SIZE) loader.write(image) return ( loader.get_pixbuf(), file_url, ) + extra
def load_icon_cache_zip(zip_path): """ Load icon cache from zipped archive :param zip_path: Full path of the zip archive :return: Dict with icon names and Gdkpixbuf object """ with ZipFile(zip_path, 'r') as archive: icon_path = os.path.join('cv_gtk3', 'resources', 'mana') files = [ path for path in archive.namelist() if os.path.isfile(path.startswith(icon_path)) ] icons = {} for file in files: with archive.open(file) as data: try: loader = GdkPixbuf.PixbufLoader() loader.write(data.read()) pixbuf = loader.get_pixbuf() loader.close() # Strip filename extension icon_name = os.path.splitext(file)[0] icons[icon_name] = pixbuf except Exception as ex: print( 'Error while loading icon file "{0}"\n{1}'.format( file, ex)) return icons
def get_thumbnail_from_file(fileobj, boundary): """Like get_thumbnail() but works with files that can't be reopened. This is needed on Windows where NamedTemporaryFile can't be reopened. Returns Pixbuf or None. Thread-safe. """ assert fileobj try: path = fileobj.name assert is_fsnative(path), path return get_thumbnail(path, boundary) except GLib.GError: try: loader = GdkPixbuf.PixbufLoader() loader.set_size(*boundary) loader.write(fileobj.read()) loader.close() fileobj.seek(0, 0) # can return None in case of partial data return loader.get_pixbuf() except (GLib.GError, EnvironmentError): pass
def new_popup(self, nid, summary, body, actions, icon, timeout=10 * 1000, show_timeout=False): """Create a new Popup instance.""" if len(self._notify_stack) == self.max_popups: oldest = self._notify_stack[0] oldest.hide_notification() self.popup_closed(oldest.nid, 4) image = None if icon and icon[0] == "png": img_data = icon[3] loader = GdkPixbuf.PixbufLoader() loader.write(img_data) loader.close() image = loader.get_pixbuf() popup = Popup(self, nid, summary, body, actions, image=image, timeout=timeout // 1000, show_timeout=show_timeout) self._notify_stack.append(popup) self._offset += self._notify_stack[-1].h return popup
def svg_str_to_pixbuf(svg_string): ''' Load pixbuf from SVG string ''' pl = GdkPixbuf.PixbufLoader() pl.write(svg_string) pl.close() pixbuf = pl.get_pixbuf() return pixbuf
def ora_thumbnail(infile, outfile, size): """Extracts an OpenRaster file's thumbnail to PNG, with scaling.""" # Extract a GdkPixbuf from the OpenRaster file with zipfile.ZipFile(infile) as zf: png_data = zf.read('Thumbnails/thumbnail.png') loader = GdkPixbuf.PixbufLoader() loader.write(png_data) loader.close() pixbuf = loader.get_pixbuf() # Scale if needed orig_w = pixbuf.get_width() orig_h = pixbuf.get_height() if orig_w > size or orig_h > size: scale_factor = float(size) / max(orig_w, orig_h) new_w = int(orig_w * scale_factor) new_h = int(orig_h * scale_factor) pixbuf = pixbuf.scale_simple( new_w, new_h, GdkPixbuf.InterpType.BILINEAR, ) # Save. The output file is a temporary one created by # GNOME::ThumbnailFactory, which overwrites any options we add # with its own Thumb::MTime and Thumb::URI. pixbuf.savev(outfile, "png", [], [])