def _load_image(self): """ Set the default image """ possible_image = self._path + '/.folder'.replace('//', '/') if os.path.exists(possible_image): image_path = possible_image elif os.path.exists(possible_image + '.png'): image_path = possible_image + '.png' elif os.path.exists(possible_image + '.jpg'): image_path = possible_image + '.jpg' elif os.path.exists(possible_image + '.jpeg'): image_path = possible_image + '.jpeg' else: if os.path.exists(self._path): image_path = ICON_LOGO_MEDIUM else: image_path = ICON_ERROR_BIG self.pixbuf_small_video = Pixbuf.new_from_file_at_size( image_path, self._series_image_small_size, self._series_image_small_size) self.image_big = Gtk.Image.new_from_pixbuf( Pixbuf.new_from_file_at_size(image_path, self._series_image_big_size + 60, self._series_image_big_size))
def lock(self, _): self.__LOCKED = not self.__LOCKED self._ui.LOCK.set_from_pixbuf( Pixbuf.new_from_file_at_size( 'img/lock.png', 24, 24)) if self.__LOCKED else self._ui.LOCK.set_from_pixbuf( Pixbuf.new_from_file_at_size('img/unlock.png', 24, 24))
def get_pixbuf_for_game(game_slug, icon_type="banner", is_installed=True): if icon_type in ("banner", "banner_small"): size = BANNER_SIZE if icon_type == "banner" else BANNER_SMALL_SIZE default_icon = DEFAULT_BANNER icon_path = os.path.join(settings.BANNER_PATH, "%s.jpg" % game_slug) elif icon_type == "icon": size = ICON_SIZE default_icon = DEFAULT_ICON icon_path = os.path.join(settings.ICON_PATH, "lutris_%s.png" % game_slug) if not os.path.exists(icon_path): icon_path = default_icon try: pixbuf = Pixbuf.new_from_file_at_size(icon_path, size[0], size[1]) except GLib.GError: pixbuf = Pixbuf.new_from_file_at_size(default_icon, size[0], size[1]) if not is_installed: transparent_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( UNAVAILABLE_GAME_OVERLAY, size[0], size[1] ) transparent_pixbuf = transparent_pixbuf.scale_simple( size[0], size[1], GdkPixbuf.InterpType.NEAREST ) pixbuf.composite(transparent_pixbuf, 0, 0, size[0], size[1], 0, 0, 1, 1, GdkPixbuf.InterpType.NEAREST, 100) return transparent_pixbuf return pixbuf
def capture_image(self, x, y, width, height, window): pb = pixbuf.new(colorspace.RGB, True, 8, width, height) # mask the pixbuf if we have more than one screen root_width, root_height = window.get_width(), window.get_height() pb2 = pixbuf.new(colorspace.RGB, True, 8, root_width, root_height) pb2 = gdk.pixbuf_get_from_window(window, 0, 0, root_width, root_height) pb2 = self.mask_pixbuf(pb2, root_width, root_height) pb2.copy_area(x, y, width, height, pb, 0, 0) if not pb: print('Invalid Pixbuf') exit(EXIT_INVALID_PIXBUF) if self.use_clipboard: self.save_clipboard(pb) else: self.save_file(pb, width, height) # call_exec returns immediately if self.command is None self.call_exec(width, height) # daemonize here so we don't mess with the CWD on subprocess if self.use_clipboard: daemonize() else: # exit here instead of inside save_file self.on_exit(width, height)
def on_open_image2(self, widget, path, img_pop): # paths = self.get_selected_items() model = self.get_model() # if paths: # path = paths[0] iter = model.get_iter(path) pixbuf_format, width, height = Pixbuf.get_file_info(model[iter][0]) if height > 1080 or width > 1900: pixbuf = Pixbuf.new_from_file_at_scale(model[iter][0], 1900, 1080, True) else: pixbuf = Pixbuf.new_from_file(model[iter][0]) # img = Gtk.Image.new_from_pixbuf(pixbuf) # img.show_all() # pb = img.get_pixbuf() # if pb.get_height() > 1080 # scroll = Gtk.ScrolledWindow() # scroll.set_pre # scroll.add(img) # pop = Gtk.Window.new(1) # pop.add(img) # pop.set_position(3) # pop.show_all() # pop.connect('button-release-event', self.on_pop_click) # self.img_menu_item.set_image(img) img_pop.set_pixbuf(pixbuf) img_pop.popup()
def on_copy_image(self, widget, cc): global data data = False cp = self.notebook.get_current_page() if cp == 1: copy_iitem_image = cc[-cp] tree = ET.parse('history.xml') root = tree.getroot() clipboard.clear() pixbuf0 = Pixbuf.new_from_file("images/"+copy_iitem_image) os.remove("images/"+copy_iitem_image) self.notebook.remove_page(cp) clipboard.set_image(pixbuf0) if cp > 1: copy_iitem_image = cc[-cp] tree = ET.parse('history.xml') root = tree.getroot() clipboard.clear() pixbuf0 = Pixbuf.new_from_file("images/"+copy_iitem_image) os.remove("images/"+copy_iitem_image) self.notebook.remove_page(cp) clipboard.set_image(pixbuf0) sleep(0.1) self.on_row_clicked2() self.destroy()
def on_iconview_key_press_event(self, widget, event): to_remove = [] cats = {48: 0, 49: 1, 50: 2, 51: 3, 52: 4, 53: 5, 54: 6, 55: 7, 56: 8, 57: 9} # the larger number is the keyval equvilent to the smaller number #What do cats use to make coffee? A purrcolator! XD if event.keyval in cats: print("Key {0} has been pressed".format(cats[event.keyval])) for row in (self.temp_index): row_elements = row.split(",") for each in self.thumb_view.get_selected_items(): path = gtk.TreePath(each) # thumb position (numeric value) within the gallery view treeiter = self.model.get_iter(path) value = self.model.get_value(treeiter, 1) # thumbnail path if value == row_elements[1] and row_elements[3] == "0": print("match found") print(row) to_remove.append(row) #takes a snaptshot of the row, adds to to_remove list for iteration and removal from self.temp_index later rep_str = (row) rep_str = rep_str.split(",") # prepares original row for category replacement new_str_seq = (rep_str[0],rep_str[1],rep_str[2],str(cats[event.keyval])) rep_str = ",".join(new_str_seq) print(rep_str) self.temp_index.append(rep_str) for row in self.temp_index[:]: row_elements = row.split(",") for each in to_remove: if each == row: self.temp_index.remove(row) print("row removed") print("temp index updated") to_remove[:] = [] self.model.clear() print("Building new thumbs!") print(strftime("%Y-%m-%d %H:%M:%S", gmtime())) for line in self.temp_index[:40]: attribute = (line.split(",")) thumb_loc = attribute[1] file_loc = attribute[2] category = attribute[3] if category == '0' and os.path.isfile(thumb_loc) == False: # !!!RESEARCH REQUIRED TO LOAD EXISTING FILE print("thumb does not exist") dir_parser.thumbs_generator(file_loc, thumb_loc) pixbuf = Pixbuf.new_from_file(thumb_loc) pixbuf = pixbuf.scale_simple(self.desired_width, self.desired_height, GdkPixbuf.InterpType.BILINEAR) self.model.append([pixbuf, thumb_loc]) elif category == '0' and os.path.isfile(thumb_loc) == True: print("thumb does exist") pixbuf = Pixbuf.new_from_file(thumb_loc) pixbuf = pixbuf.scale_simple(self.desired_width, self.desired_height, GdkPixbuf.InterpType.BILINEAR) self.model.append([pixbuf, thumb_loc]) print("new thumbs created!") print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
def get_log(self, out): base64image = out try: raw_data = base64.b64decode(base64image) input_stream = Gio.MemoryInputStream.new_from_data(raw_data, None) pixbuf = Pixbuf.new_from_stream(input_stream, None) except: # error image raw_data = base64.b64decode( """iVBORw0KGgoAAAANSUhEUgAAAZAAAAFACAYAAACSgSrjAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4QoWAAsIwyEjnAAAEPhJREFUeNrt3b9uW+cZwOFXhhFAHjPGgzIFCQu4BbQF6SBfgZyhRW7Bvox2ypwhvgR3SZasydAiG4EmQJUgQwEO7ujRKoIg7uDDhpYoiufwO+d8f54HKES0saNSlF6+H3n0iwC2ujg5/eTi5PQT9wRsd+QugGuDIyLi7Yj4vvuvHkTEi8Vq6c6BDXfcBfDm8OgGxZOIuN/958litVwPFsAGAjcOkY8i4u9X/us/LlbLf7h3wACBrdtHHMXdeBXfRcTi6v8cR/H7eBW/OMqC1xxhQWexWka8io+3DI+IiEW8io8ND7CBwLYN5DgiXt7yj91brJaX7i2wgUD88N6H65tf7fGPf3Xlz4ANBBrdOqJ7h9VZRHy95x97uFgtv9l4xxYYINDwIHkZEcd7/uOXi9XynnuN1jnCounto/v4rMfwiIg47v6Ma0OwgUDDQ+R3EfHPiLjb84/+EhF/WKyW/3IvYgOBNn0+YHhE92c+d/dhgECb28dfIuKjA/6Kj7q/A5rkCItWh8f9eP3LEt8+8K96EREPFqvlc/cqNhCoe3Csb36WYHhE93d8duXvBhsIVDpEziPii8R/7aPFavmlexcDBOrdPtadj/uJ//rnoRtCYxxh0czwuNL5SE03BBsIVDxEtnU+UtMNwQCBmraPHZ2P5P863RBa4QiL6t3S+Uj+r9MNwQYC9Wwg+3Q+UtMNwQYCperZ+UhNNwQbCBS6dQzpfKSmG4IBAgUPkj6dj9R0Q6iaIyyq3D66j307H6nphmADgQKHyNDOR2q6Id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5JRj7B+eO/D+OCnbyP8pl2m4wc0vP6Z+3DjZ3BZG8j6XVdd5+NrX0+AST1crJbfbLwDtpwBsjFIXoZf1Q4wtcvFanlvzH/BKC+i63wAzG70bsiYR1g6HwDzGrUbMubbeHU+AOY1ajdkrCMsnQ+APIzWDUl+hNX9bvrvw69qB8jFi4h4sFgtn2e5geh8AGRrlG5I0g2k63x84WsFkKVHi9Xyy6wGiM4HQBGSdkMOPsLS+QAoRtJuSKoNROcDoBxJuiEHDZCNzsd34Ve1A5TiIo7i4G7IQUdYOh8ARUrSDTl0A9H5ACjXQd2QQRvID+99uL6p8wFQrq+u/EwfdwPR+QCoyuBuyOAjLJ0PgCoM7ob0OsLS+QCozuBuyJAjLJ0PgLoM6oYMeRFd5wOgLoO6IX2PsHQ+AOrUuxuy9xGWzgdA9Xp1Q27dQHQ+AJrRqxuy1wai8wHQlL26IUd7bB86HwBt2asbcmfX8ND5AGjSXt2Q2zYQnQ+Adu3shhzdtH3ofAA0b2c3ZOsRls4HAHFLN+SmDUTnA4C1rd2QNzYQnQ8AttjaDTna2Dp0PgC4ybVuyLUjLJ0PALa41g25s94+uo86HwBsc60bsnmEpfMBwC5vdEM2X0TX+QBglze6IesjLJ0PAPbx/27Ikc4HAD29iIgHdyLiU8MDgB7ejohP/wdfG3IxFRM1PgAAAABJRU5ErkJggg==""" ) input_stream = Gio.MemoryInputStream.new_from_data(raw_data, None) pixbuf = Pixbuf.new_from_stream(input_stream, None) self.image = Gtk.Image() self.image.set_from_pixbuf(pixbuf) self.image.show() scrolledwindow = Gtk.ScrolledWindow() scrolledwindow.set_hexpand(True) scrolledwindow.set_vexpand(True) scrolledwindow.add(self.image) scrolledwindow.show() return scrolledwindow
def get_pixbuf_for_game(game_slug, icon_type="banner", is_installed=True): if icon_type in ("banner", "banner_small"): size = BANNER_SIZE if icon_type == "banner" else BANNER_SMALL_SIZE default_icon = DEFAULT_BANNER icon_path = os.path.join(settings.BANNER_PATH, "%s.jpg" % game_slug) elif icon_type == "icon": size = ICON_SIZE default_icon = DEFAULT_ICON icon_path = os.path.join(settings.ICON_PATH, "lutris_%s.png" % game_slug) if not os.path.exists(icon_path): icon_path = default_icon try: pixbuf = Pixbuf.new_from_file_at_size(icon_path, size[0], size[1]) except GLib.GError: pixbuf = Pixbuf.new_from_file_at_size(default_icon, size[0], size[1]) if not is_installed: transparent_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( UNAVAILABLE_GAME_OVERLAY, size[0], size[1]) transparent_pixbuf = transparent_pixbuf.scale_simple( size[0], size[1], GdkPixbuf.InterpType.NEAREST) pixbuf.composite(transparent_pixbuf, 0, 0, size[0], size[1], 0, 0, 1, 1, GdkPixbuf.InterpType.NEAREST, 100) return transparent_pixbuf return pixbuf
def setImage(self, fileName): if not self.settingsManager.resizeImage: mpixbuf = Pixbuf.new_from_file(fileName) else: mpixbuf = Pixbuf.new_from_file_at_scale(fileName, self.iCurWidth, self.iCurHeight, True) self.currentFile = fileName Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT_IDLE, self.GtkSetImage, mpixbuf)
def load_sample_image(self, fname): """Загрузка изображения с образцом чернил в определитель цвета.""" tmppbuf = Pixbuf.new_from_file(fname) self.pixbufCX = tmppbuf.get_width() self.pixbufCY = tmppbuf.get_height() # создаём новый, строго заданного формата, мало ли что там загрузилось self.pixbuf = Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, self.pixbufCX, self.pixbufCY) # на случай наличия альфа-канала в исходном изображении self.pixbuf.fill(0xffffffff) tmppbuf.composite(self.pixbuf, 0, 0, self.pixbufCX, self.pixbufCY, 0, 0, 1.0, 1.0, GdkPixbuf.InterpType.TILES, 255); self.pixbufPixels = self.pixbuf.get_pixels() self.pixbufChannels = self.pixbuf.get_n_channels() self.pixbufRowStride = self.pixbuf.get_rowstride() #self.swImgView.set_max_content_width(self.pixbufCX) #self.swImgView.set_max_content_height(self.pixbufCY) self.imgView.set_from_pixbuf(self.pixbuf) self.swImgView.get_hadjustment().set_value(0) self.swImgView.get_vadjustment().set_value(0) # self.lstoreSamples.clear() self.update_sample_count() self.compute_average_color()
def search_worker(self, query): try: self.extmgr.search(query) except Exception as error: GLib.idle_add(self.show_error, error) GLib.idle_add(self.restore_search_button) for index, result in enumerate(self.extmgr.results): # Download the image into a buffer and render it with pixbuf try: img_buffer = self.extmgr.get_image(self.extmgr.get_uuid(index)) except Exception as error: GLib.idle_add(self.show_error, error) GLib.idle_add(self.restore_search_button) # Check if the extension icon is local (faster searching) if img_buffer == None: pixbuf = Pixbuf.new_from_file( os.path.join(os.path.dirname(__file__), "plugin.png")) else: img_buffer = Gio.MemoryInputStream.new_from_data( img_buffer, None) pixbuf = Pixbuf.new_from_stream(img_buffer, None) pixbuf = pixbuf.scale_simple(32, 32, InterpType.BILINEAR) self.extmgr.results[index]["pixbuf"] = pixbuf GLib.idle_add(self.display_search_results)
def complete(manga_data, server): if server != self.server or manga_data['slug'] != self.manga_slug: return False self.manga_data = manga_data # Populate manga card try: cover_data = self.server.get_manga_cover_image( self.manga_data.get('cover')) except Exception as e: cover_data = None user_error_message = log_error_traceback(e) if user_error_message: self.show_notification(user_error_message) if cover_data is not None: cover_stream = Gio.MemoryInputStream.new_from_data( cover_data, None) pixbuf = Pixbuf.new_from_stream_at_scale( cover_stream, 174, -1, True, None) else: pixbuf = Pixbuf.new_from_resource_at_scale( '/info/febvre/Komikku/images/missing_file.png', 174, -1, True) self.builder.get_object('cover_image').set_from_pixbuf(pixbuf) self.builder.get_object('authors_value_label').set_markup( '<span size="small">{0}</span>'.format( ', '.join(self.manga_data['authors'] ) if self.manga_data['authors'] else '-')) self.builder.get_object('genres_value_label').set_markup( '<span size="small">{0}</span>'.format( ', '.join(self.manga_data['genres'] ) if self.manga_data['genres'] else '-')) self.builder.get_object('status_value_label').set_markup( '<span size="small">{0}</span>'. format(_(Manga.STATUSES[self.manga_data['status']]) ) if self.manga_data['status'] else '-') self.builder.get_object('scanlators_value_label').set_markup( '<span size="small">{0}</span>'.format( ', '.join(self.manga_data['scanlators'] ) if self.manga_data['scanlators'] else '-')) self.builder.get_object('server_value_label').set_markup( '<span size="small"><a href="{0}">{1} [{2}]</a>\n{3} chapters</span>' .format( self.server.get_manga_url(self.manga_data['slug'], self.manga_data.get('url')), html.escape(self.server.name), self.server.lang.upper(), len(self.manga_data['chapters']))) self.builder.get_object('synopsis_value_label').set_text( self.manga_data['synopsis'] or '-') self.activity_indicator.stop() self.show_page('manga') return False
def __init__(self, session=None, lista_comics_id=None): ImageFile.LOAD_TRUNCATED_IMAGES = True if session is None: self.session = Entidades.Init.Session() else: self.session = session self.handlers = { 'Guardar': self.Guardar, 'click_mouse': self.click_mouse, 'crear_globo': self.crear_globo, 'actualizar_imagen': self.actualizar_imagen, 'seleccion_arbol': self.seleccion_arbol, 'guardar_coordenadas': self.guardar_coordenadas, 'mover_texto': self.mover_texto, 'delete_nodo': self.delete_nodo } self.cataloged_pix = Pixbuf.new_from_file_at_size( '../iconos/Cataloged.png', 32, 32) self.comicbooks_manager = Comicbooks(session=self.session, lista_comics_id=lista_comics_id) builder = Gtk.Builder() builder.add_from_file("../Glade_files/Comicbook_Editor.glade") builder.connect_signals(self.handlers) self.window = builder.get_object("Comicbook_editor") self.imagen_pagina = builder.get_object("imagen_pagina") self.spinner_pos_x_0 = builder.get_object("spinner_pos_x_0") self.spinner_pos_y_0 = builder.get_object("spinner_pos_y_0") self.spinner_pos_x_1 = builder.get_object("spinner_pos_x_1") self.spinner_pos_y_1 = builder.get_object("spinner_pos_y_1") self.arbol = builder.get_object('arbol') self.liststore_arbol = builder.get_object("liststore_arbol") self.entry_text = builder.get_object("entry_text") self.labels_coords = builder.get_object('labels_coords') self.event_box = builder.get_object("event_box") self.window.set_title("Editor") self.app_icon = Pixbuf.new_from_file_at_size( '../iconos/iconoBabelComics-buuf.png', 32, 32) self.window.set_icon_from_file('../iconos/iconoBabelComics-buuf.png') self.window.set_default_icon_list([self.app_icon]) self.comicbook = None self.last_id_used = 0 self.diccionario_globos = {} self.current_node = 0 #atributos para capturar y crear los globos de texto self.cantidad_clicks = 0 self.modo = self.CREANDO_GLOBO self.lista_clicks = [0, 0, 0, 0] if lista_comics_id is not None: self.load_page(lista_comics_id[0]) self.load_json_file()
def show_app(builder,iconview,treepath): global stage global SubCategoryList global ProgramList #Is AlreadyOpen Bool global ProgramViewOpen #Which Subcategory global ProgramName #ShowDialog if not already open if ProgramViewOpen != True: AppWin = builder.get_object('ApplicationDialog_Install') ProgramName = ProgramList[treepath.get_indices()[0]] Data = db.read_attributes(ProgramName) #Set Name, Short and Long description, Symbol, Screenshot Title = builder.get_object('AD_App_Label') Title.set_text(Data[1]) #Short Description ShortDescription = builder.get_object('AD_ShortDescription') ShortDescription.set_text(Data[2]) #Long Description LongDescription = builder.get_object('AD_LongDescription') LongDescription.set_text(Data[3]) #Symbol Symbol = builder.get_object('AD_Symbol') try: SymbolPixbuf = Pixbuf.new_from_file_at_size(conf.get_entry('DB','dblocation') + Data[8],64 ,64) Symbol.set_from_pixbuf(SymbolPixbuf) except: Symbol.set_from_icon_name('error-dialog',10) print('Failed To Load Symbol') #Screenshot Screenshot = builder.get_object('AD_Screenshot') try: ScreenshotPixbuf = Pixbuf.new_from_file_at_size(conf.get_entry('DB','dblocation') + Data[4],512 ,512) Screenshot.set_from_pixbuf(ScreenshotPixbuf) except: Screenshot.set_from_icon_name('error-dialog',10) print('Failed to load Screenshot') AppWin.show_all() ProgramViewOpen = True else: ErrorWinAppView = builder.get_object('AD_AVIsOpen') ErrorWinAppView.show_all()
def _get_pixbuf_pixel(pb: GdkPixbuf.Pixbuf, x, y): bytes = pb.get_pixels() n_channels = pb.get_n_channels() rowstride = pb.get_rowstride() bps = pb.get_bits_per_sample() bytes_per_pixel = int(n_channels * bps / 8) offset = y * rowstride + x * bytes_per_pixel return list(bytes[offset:offset + bytes_per_pixel])
def set_image(self, path): if os.path.exists(path): self.pixbuf_small_video = Pixbuf.new_from_file_at_size( path, self._series_image_small_size, self._series_image_small_size) self.image_big = Gtk.Image.new_from_pixbuf( Pixbuf.new_from_file_at_size(path, self._series_image_big_size + 60, self._series_image_big_size)) shutil.copy2(path, self._path + "/.folder")
def loadAndCreateThumbnails(self): if not self.updating_gui: # sacamo el hilo que puede estar creando los thumnails para la pagina anterior porque ahora la vamos a # recreear self.salir_thread = True self.liststore.clear() self.lista_pendientes.clear() self.listaComics = self.query.limit(self.limit).offset(self.offset).all() print("Cantidad de comics: {}".format(len(self.listaComics))) self.iconview.set_model(self.liststore) self.iconview.set_pixbuf_column(0) self.iconview.set_text_column(1) self.cantidadThumnailsAGenerar = len(self.listaComics) self.cantidadThumnailsGenerados = 0 self.label_contadores.set_text("0/{}".format(len(self.listaComics))) for index, comic in enumerate(self.listaComics): self.cantidadThumnailsGenerados += 1 try: nombreThumnail = self.pahThumnails + str(comic.id_comicbook) + '.jpg' cover = None if os.path.isfile(nombreThumnail): try: cover = Pixbuf.new_from_file(nombreThumnail) except: cover = Pixbuf.new_from_file(self.pahThumnails + "error_caratula.png") #cover = Pixbuf.new_from_file(self.pahThumnails + "sin_caratula.jpg") if comic.id_comicbook_info != '': self.cataloged_pix.composite(cover, cover.props.width - self.cataloged_pix.props.width, cover.props.height - self.cataloged_pix.props.height, self.cataloged_pix.props.width, self.cataloged_pix.props.height, cover.props.width - self.cataloged_pix.props.width, cover.props.height - self.cataloged_pix.props.height, 1, 1, 3, 200) cover.scale_simple(50, 10, 3) self.liststore.append([cover, comic.getNombreArchivo(), index]) else: cover = Pixbuf.new_from_file(self.pahThumnails + "sin_caratula.jpg") iter = self.liststore.append([cover, comic.getNombreArchivo(), index]) self.lista_pendientes.append((iter, comic)) except NotRarFile: print('error en el archivo ' + comic.path) except BadRarFile: print('error en el archivo ' + comic.path) self.thread_creacion_thumnails = threading.Thread(target=self.crear_thumnails_de_pagina_background) self.thread_creacion_thumnails.start() self.update_imagen_papelera()
def set_manga_cover_image(self, overlay, width, height, update=False): overlay.set_size_request(width, height) if overlay._pixbuf is None or update: manga = overlay.manga if manga.cover_fs_path is not None: overlay._pixbuf = Pixbuf.new_from_file(manga.cover_fs_path) else: overlay._pixbuf = Pixbuf.new_from_resource('/info/febvre/Komikku/images/missing_file.png') pixbuf = overlay._pixbuf.scale_simple(width, height, InterpType.BILINEAR) image = overlay.get_children()[0] image.set_from_pixbuf(pixbuf)
def load_image(self): sz_food = self.data['block_size'] * 1.2 self.pix_icon = Pixbuf.new_from_file(self.data['image_icon']) self.pix_food = Pixbuf.new_from_file_at_size( self.data['image_snake_food'], sz_food, sz_food) self.pix_arrow = Pixbuf.new_from_file_at_size(self.data['image_arrow'], 28, 28) self.pix_arrow_key = Pixbuf.new_from_file_at_size( self.data['image_arrow_key'], 28, 28) self.img_logo.set_from_pixbuf( self.pix_icon.scale_simple(24, 24, InterpType.BILINEAR))
def popular_controles(self): pb = Pixbuf.new_from_file_at_scale("imagem_dia.jpg", width=50, height=50,preserve_aspect_ratio=False) self.imagem.set_from_pixbuf(pb) self.cidade.set_text(self.conteudo['cidade']) self.descricao.set_text(self.conteudo['agora']['descricao']) self.temperatura.set_text('Temperatura: ' + self.conteudo['agora']['temperatura'] + ' graus') self.umidade.set_text('Umidade: ' + self.conteudo['agora']['umidade']) for num, value in enumerate(self.conteudo['previsoes']): if num == 1: self.previsao_dia1.set_text(value['data']) self.descricao_dia1.set_text(value['descricao']) img_url = value['imagem'] response = urllib.request.urlopen(img_url) with open("imagem_dia1.jpg", 'wb') as f: f.write(response.read()) pb = Pixbuf.new_from_file_at_scale("imagem_dia1.jpg", width=50, height=50,preserve_aspect_ratio=False) self.imagem_dia1.set_from_pixbuf(pb) self.max_min_dia1.set_text("Max: " + value['temperatura_max'] + " Min: " + value['temperatura_min']) elif num == 2: self.previsao_dia2.set_text(value['data']) self.descricao_dia2.set_text(value['descricao']) img_url = value['imagem'] response = urllib.request.urlopen(img_url) with open("imagem_dia2.jpg", 'wb') as f: f.write(response.read()) pb = Pixbuf.new_from_file_at_scale("imagem_dia2.jpg", width=50, height=50,preserve_aspect_ratio=False) self.imagem_dia2.set_from_pixbuf(pb) self.max_min_dia2.set_text("Max: " + value['temperatura_max'] + " Min: " + value['temperatura_min']) elif num == 3: self.previsao_dia3.set_text(value['data']) self.descricao_dia3.set_text(value['descricao']) img_url = value['imagem'] response = urllib.request.urlopen(img_url) with open("imagem_dia3.jpg", 'wb') as f: f.write(response.read()) pb = Pixbuf.new_from_file_at_scale("imagem_dia3.jpg", width=50, height=50,preserve_aspect_ratio=False) self.imagem_dia3.set_from_pixbuf(pb) self.max_min_dia3.set_text("Max: " + value['temperatura_max'] + " Min: " + value['temperatura_min']) elif num == 4: self.previsao_dia4.set_text(value['data']) self.descricao_dia4.set_text(value['descricao']) img_url = value['imagem'] response = urllib.request.urlopen(img_url) with open("imagem_dia4.jpg", 'wb') as f: f.write(response.read()) pb = Pixbuf.new_from_file_at_scale("imagem_dia4.jpg", width=50, height=50,preserve_aspect_ratio=False) self.imagem_dia4.set_from_pixbuf(pb) self.max_min_dia4.set_text("Max: " + value['temperatura_max'] + " Min: " + value['temperatura_min'])
def get_avatar_img_as_pixbuf(self, mode="file"): if mode == "stream": url = self.data["avatar_url"] response = urllib.request.urlopen(url) input_stream = Gio.MemoryInputStream.new_from_data( response.read(), None) pixbuf = Pixbuf.new_from_stream(input_stream, None) elif mode == "file": pixbuf = Pixbuf.new_from_file_at_size( self.get_avatar_img_file_path(), self.USER_AVATAR_SIZE, self.USER_AVATAR_SIZE, ) return pixbuf
def get_image_stream(url): pixbuf = None if "nochannel.png" in url: pixbuf = Pixbuf.new_from_file(url) else: response = urllib.request.urlopen(url) input_stream = Gio.MemoryInputStream.new_from_data( response.read(), None) pixbuf = Pixbuf.new_from_stream(input_stream, None) width = pixbuf.get_width() width_perc = (100 * 100) / width height = (pixbuf.get_height() * width_perc) / 100 pixbuf = pixbuf.scale_simple(100, height, InterpType.BILINEAR) return pixbuf
def scale_pixbuf(pixbuf: GdkPixbuf.Pixbuf, outer_width: int, outer_height): # Get original size ow = pixbuf.get_width() oh = pixbuf.get_height() # Get aspect ration ratio = Fraction(ow, oh) # Try scaling to outer_height scaled_height = outer_height scaled_width = int(ratio * outer_height) # If it is larger than outer_width, fixed by width if scaled_width > outer_width: scaled_width = outer_width scaled_height = int(scaled_width / ratio) # Now scale with calculated size return pixbuf.scale_simple(scaled_width, scaled_height, GdkPixbuf.InterpType.BILINEAR)
def getIcon(name, mime = None, size = None): d = os.path.join(r, 'icons') if mime == None: mime = 'png' n = ".".join([name, mime]) p = os.path.join(d, n) if size == None: i = Pixbuf.new_from_file(p) else: i = Pixbuf.new_from_file_at_scale(p, size, size, False) return i
def pixbuf_from_bytes(b, width, height): """Создаёт и возвращает экземпляр Gdk.Pixbuf. b - экземпляр GLib.Bytes с данными в формате PNG/JPG/..., width, height - целые, размеры изображения в пикселах, если нужен определённый размер; для загрузки "как есть" следует указывать значения <=0 или None.""" if isinstance(width, int) and width > 0: return Pixbuf.new_from_stream_at_scale(Gio.MemoryInputStream.new_from_bytes(b), width, height, None) else: return Pixbuf.new_from_stream(Gio.MemoryInputStream.new_from_bytes(b), None)
def getIcon(name, mime=None, size=None): d = os.path.join(r, 'icons') if mime == None: mime = 'png' n = ".".join([name, mime]) p = os.path.join(d, n) if size == None: i = Pixbuf.new_from_file(p) else: i = Pixbuf.new_from_file_at_scale(p, size, size, False) return i
def main(): global browser global window frontend = frontend_fill() window = gtk.Window() window.connect('destroy', gtk.main_quit) window.set_title(appname) window.set_icon(Pixbuf.new_from_file(app_icon)) rootsize = tkinter.Tk() if rootsize.winfo_screenheight() > 700: window.set_resizable(False) window.set_size_request(800, 550) else: window.set_resizable(True) window.set_size_request(600, 500) window.set_position(gtk.WindowPosition.CENTER), browser = webkit.WebView() swindow = gtk.ScrolledWindow() window.add(swindow) swindow.add(browser) window.show_all() browser.connect("navigation-requested", functions) browser.load_html_string(frontend, "file://{0}/frontend/".format(app_dir)) settings = browser.get_settings() settings.set_property('enable-default-context-menu', False) browser.set_settings(settings) gtk.main()
def load_plants(): subdir = 'funkenschlagPics/kw' path = join(base_dir, subdir) fns = ( 'funkkart_03a.jpg', 'funkkart_04a.jpg', 'funkkart_05a.jpg', 'funkkart_06a.jpg', 'funkkart_07a.jpg', 'funkkart_08a.jpg', 'funkkart_09a.jpg', 'funkkart_10a.jpg', 'funkkart_11a.jpg', 'funkkart_12a.jpg', 'funkkart_13a.jpg', 'funkkart_14a.jpg', 'funkkart_15a.jpg', 'funkkart_16a.jpg', 'funkkart_17a.jpg', 'funkkart_18a.jpg', 'funkkart_19a.jpg', 'funkkart_20a.jpg', 'funkkart_21a.jpg', 'funkkart_22a.jpg', 'funkkart_23a.jpg', 'funkkart_24a.jpg', 'funkkart_25a.jpg', 'funkkart_26a.jpg', 'funkkart_27a.jpg', 'funkkart_28a.jpg', 'funkkart_29a.jpg', 'funkkart_30a.jpg', 'funkkart_31a.jpg', 'funkkart_32a.jpg', 'funkkart_33a.jpg', 'funkkart_34a.jpg', 'funkkart_35a.jpg', 'funkkart_36a.jpg', 'funkkart_37a.jpg', 'funkkart_38a.jpg', 'funkkart_39a.jpg', 'funkkart_40a.jpg', 'funkkart_42a.jpg', 'funkkart_44a.jpg', 'funkkart_46a.jpg', 'funkkart_50a.jpg', 'stufe_3_a.jpg', 'blass.png', 'blocker.jpg' ) out = [] for fn in map(lambda x:join(path, x), fns): pix = Pixbuf.new_from_file(fn) #pix = pix.scale_simple(48, 48, InterpType.HYPER) out.append(pix) return tuple(out)
def best_zoom(self,widget): self.zoom_actual = 2 rect = self.view_port_img.get_allocation() pixbuf = Pixbuf.new_from_file(self.v_item_actual) ancho_pixbuf = pixbuf.get_width() alto_pixbuf = pixbuf.get_height() if ancho_pixbuf > alto_pixbuf: ancho = int(rect.width - 4) relacion = (alto_pixbuf*100)/ancho_pixbuf alto = int(ancho * relacion/100) else: alto = int(rect.height - 4) relacion = (ancho_pixbuf*100 - 4)/alto_pixbuf ancho = int(alto * (relacion/100)) if alto > rect.height: alto = int(rect.height - 4) relacion = (ancho_pixbuf*100 - 4)/alto_pixbuf ancho = int(alto * (relacion/100)) elif ancho > rect.width: ancho = int(rect.width - 4) relacion = (alto_pixbuf*100)/ancho_pixbuf alto = int(ancho * relacion/100) prev_pixbuf = pixbuf.scale_simple(ancho, alto, v_inter) self.image.set_from_pixbuf(prev_pixbuf) self.image.show()
def main(): global browser global window frontend = frontend_fill() window = gtk.Window() window.connect('destroy', gtk.main_quit) window.set_title("Linux Lite Control Center") window.set_icon(Pixbuf.new_from_file("{0}/litecc.png".format(app_dir))) window.set_size_request(880, 660) # Valtam do we need to resize window? window.set_resizable(False) window.set_position(gtk.WindowPosition.CENTER), browser = webkit.WebView() swindow = gtk.ScrolledWindow() window.add(swindow) swindow.add(browser) window.show_all() browser.connect("navigation-requested", functions) browser.load_html_string(frontend, "file://{0}/frontend/".format(app_dir)) # no right click menu settings = browser.get_settings() settings.set_property('enable-default-context-menu', False) browser.set_settings(settings) # Engage gtk.main()
def dec_zoom(self,widget): if self.zoom_actual <= 6: self.zoom_actual = self.zoom_actual + 1 if self.zoom_actual == 1: v_zoom = 1.0 elif self.zoom_actual == 2: v_zoom = 1.5 elif self.zoom_actual == 3: v_zoom = 2.0 elif self.zoom_actual == 4: v_zoom = 2.5 elif self.zoom_actual == 5: v_zoom = 3.0 elif self.zoom_actual == 6: v_zoom = 3.5 elif self.zoom_actual == 7: v_zoom = 4.0 pixbuf = Pixbuf.new_from_file(self.v_item_actual) ancho_pixbuf = pixbuf.get_width() alto_pixbuf = pixbuf.get_height() ancho = ancho_pixbuf / v_zoom alto = alto_pixbuf / v_zoom prev_pixbuf = pixbuf.scale_simple(ancho, alto, v_inter) self.image.set_from_pixbuf(prev_pixbuf) self.image.show()
def _cb_open(self, button): dlg_open = Gtk.FileChooserDialog( "Open Image", button.get_toplevel(), Gtk.FileChooserAction.OPEN, ( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK )) dlg_open.set_default_response(1) dlg_open.set_select_multiple(True) filef = Gtk.FileFilter() filef.add_pixbuf_formats() dlg_open.set_filter(filef) if dlg_open.run() == Gtk.ResponseType.OK: for f in dlg_open.get_filenames(): img = Pixbuf.new_from_file_at_size(f, 128, 128) name = f.split('/')[-1] if len(name) > 18: name = name[:8] + '...' + name[-8:] self.queue_ls.append([img, name, f]) dlg_open.destroy()
def get_pixbuf_for_game(game_slug, size=ICON_SIZE, is_installed=True): width = size[0] height = size[1] icon_path = os.path.join(settings.DATA_DIR, "banners", "%s.jpg" % game_slug) if not os.path.exists(icon_path): icon_path = MISSING_ICON try: pixbuf = Pixbuf.new_from_file_at_size(icon_path, width, height) except GLib.GError: pixbuf = Pixbuf.new_from_file_at_size(MISSING_ICON, width, height) if not is_installed: transparent_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(UNAVAILABLE_GAME_OVERLAY, width, height) transparent_pixbuf = transparent_pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.NEAREST) pixbuf.composite(transparent_pixbuf, 0, 0, width, height, 0, 0, 1, 1, GdkPixbuf.InterpType.NEAREST, 100) return transparent_pixbuf return pixbuf
def load_icons(): """ Load pympress icons from the pixmaps directory (usually :file:`/usr/share/pixmaps` or something similar). :return: loaded icons :rtype: list of :class:`Gtk.gdk.Pixbuf` """ # If pkg_resources fails, load from directory icon_path = "/usr/share/pixmaps/" icon_names = glob.glob(icon_path + "pympress*") if not icon_names: icon_path = "share/pixmaps/" icon_names = glob.glob(icon_path + "pympress*") icons = [] for icon_name in icon_names: if os.path.splitext(icon_name)[1].lower() != ".png": continue # If pkg_resources fails, load from directory try: icon_pixbuf = Pixbuf.new_from_file(icon_name) icons.append(icon_pixbuf) except Exception as e: print(e) return icons
def thread_scanning(self,flag,ip_range,start,end): for i in range(int(start),int(end)): ip=ip_range[0]+"."+ip_range[1]+"."+ip_range[2]+"."+str(i) proc1 = subprocess.Popen("arping -c 1 "+ip+" | head -n 2 | tail -n 1 | awk '{print $5,$6}'" , shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) proc = subprocess.Popen("smbclient -NL "+ip, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) str1=["",""] for line in proc1.stdout: str1 = line.replace("[","").replace("]","").split(" ") if str1[0]=="broadcast(s))": proc2 = subprocess.Popen("ifconfig | head -n 1 | awk '{print $5}'", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) for line2 in proc2.stdout: str1[0]=line2.upper() str1[1]="0ms" for line in proc.stderr: if('Domain' in line): hostname =line[line.find("[")+1:line.find("]")] if hostname=="WORKGROUP": proc_nmblookup = subprocess.Popen("nmblookup -A "+ip+" | head -n 2 | tail -n 1 | awk '{print $1 }'", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) for line in proc_nmblookup.stdout: hostname=line.replace("\n","").upper() pixbuf = Pixbuf.new_from_file("/usr/share/shareviewer/media/computer.png") self.devices+=1 par = self.model.append(None ,[pixbuf,ip.strip(),hostname,str1[0].replace("\n",""),str1[1].replace("ms"," ms").replace("\n","")]) break; for line1 in proc.stdout: if line1.find("Disk")!=-1: share=line1.strip().replace("Disk","").replace("Printer Drivers","").replace("Remote Admin","").replace("Default share","").replace("\n","") pixbuf = Gtk.IconTheme.get_default().load_icon("gtk-directory", 16, 0) child = self.model.append(par,[pixbuf,share,"","",""]) self.count+=1
def __init__(self, winParent, show = False): # Retrieve the translators list translators = [] for line in readlines(FILE_TRANSLATORS, False): if ':' in line: line = line.split(':', 1)[1] line = line.replace('(at)', '@').strip() if line not in translators: translators.append(line) # Load the user interface builder = Gtk.Builder() builder.add_from_file(FILE_UI_ABOUT) # Obtain widget references self.dialog = builder.get_object("dialogAbout") # Set various properties self.dialog.set_program_name(APP_NAME) self.dialog.set_version('Version %s' % APP_VERSION) self.dialog.set_comments(APP_DESCRIPTION) self.dialog.set_website(APP_URL) self.dialog.set_copyright(APP_COPYRIGHT) self.dialog.set_authors(['%s <%s>' % (APP_AUTHOR, APP_AUTHOR_EMAIL)]) #self.dialog.set_license_type(Gtk.License.GPL_2_0) self.dialog.set_license('\n'.join(readlines(FILE_LICENSE, True))) self.dialog.set_translator_credits('\n'.join(translators)) # Retrieve the external resources links for line in readlines(FILE_RESOURCES, False): resource_type, resource_url = line.split(':', 1) self.dialog.add_credit_section(resource_type, (resource_url,)) icon_logo = Pixbuf.new_from_file(FILE_ICON) self.dialog.set_logo(icon_logo) self.dialog.set_transient_for(winParent) # Optionally show the dialog if show: self.show()
def get_scaled_image(path,image_width): """ Get a image scaled according to specified image_width. A new GDK Pixbuf is obtained for the given image path. New height of image is calculated according to specified image width. Pixbuf is scaled simply with parameters : destination image_width destination image_height the interpolation of the transformation(GDK Interp_Type) @param : path (Image location) @param : image_width @return : scaled_pix """ default_image_width = image_width try: pixbuf = Pixbuf.new_from_file(path) except Exception as msg: return get_scaled_image(p2psp_logo_path,image_width) pix_w = pixbuf.get_width() pix_h = pixbuf.get_height() new_h = (pix_h * default_image_width) / pix_w scaled_pix = pixbuf.scale_simple(default_image_width, new_h, 1) return scaled_pix
def load_map(map_nr): subdir = 'localized/en/images/Funkenschlag/' path = join(base_dir, subdir) fns = ('usa.jpg', 'deut.jpg', 'frankreich.jpg', 'italien.jpg', 'bw.jpg') pix = Pixbuf.new_from_file(join(path, fns[map_nr])) return pix
def on_about(self, btn): """""" about = AboutDialog() about.set_program_name(conf.PRG_NAME) about.set_version("v " + conf.PRG_VERS) about.set_copyright(conf.PRG_ABOUT_COPYRIGHT) about.set_comments(conf.PRG_ABOUT_COMMENTS) about.set_website(conf.PRG_WEBSITE) about.set_website_label(conf.PRG_WEBSITE) about.set_license(Io.get_data(conf.PRG_LICENSE_PATH)) pixbuf = Pixbuf.new_from_file_at_size(conf.PRG_LOGO_PATH, conf.PRG_ABOUT_LOGO_SIZE, conf.PRG_ABOUT_LOGO_SIZE) about.set_logo(pixbuf) pixbuf = Pixbuf.new_from_file_at_size(conf.PRG_LOGO_PATH, conf.PRG_ABOUT_LOGO_SIZE, conf.PRG_ABOUT_LOGO_SIZE) about.set_icon(pixbuf) about.run() about.destroy()
def run(self): builder.get_object('spinner_overlay').show() url = "/".join([self.api.API_BASE,"users",self.user,"wallpapers"]) data = json.loads(urllib2.urlopen(url).read()) done = 0 currWallpaperNr = 0; while not done: for wallpaper in data['response']: # print wallpaper currWallpaperNr = currWallpaperNr + 1; if currWallpaperNr == 1: txt = "Wallpaper" else: txt = "Wallpapers" self.headerBar.set_subtitle(str(currWallpaperNr) + " " + txt) if not os.path.isfile(self.CACHE_DIR + str(wallpaper['id'])): file = open(self.CACHE_DIR + str(wallpaper['id']),'w') file.write(urllib2.urlopen(wallpaper['image']['thumb']['url']).read()) file.close() pxbf = Pixbuf.new_from_file(self.CACHE_DIR + str(wallpaper['id'])) self.listStore.append([ str(wallpaper["id"]), wallpaper["image"]["url"], pxbf]) if not data['pagination']['next']: data['pagination']['next'] = data['pagination']['current']+1 data = json.loads(urllib2.urlopen(url + "?page=" + str(data['pagination']['next'])).read()) #print "> URL: %s\n> PAGE: %s \n ===========\n" % (url + "?page=" + str(data['pagination']['next']),str(data['pagination']['current'])), data['response'] if len(data['response']) == 0: done = 1 builder.get_object('spinner_overlay').hide()
def set_cover_from_tags(bean): try: ext = get_file_extension(bean.path) if ext == ".mp3": data = _get_pic_from_mp3(ID3(bean.path)) elif ext == ".flac": data = _get_pic_from_flac(FLAC(bean.path)) else: return None if data: filename = os.path.join(COVERS_DIR, str(crc32(bean.path)) + '.jpg') fd = NamedTemporaryFile() fd.write(data.data) pixbuf = Pixbuf.new_from_file(fd.name) pixbuf.savev(filename, "jpeg", ["quality"], ["90"]) fd.close() bean.image = filename basename = os.path.splitext(os.path.basename(filename))[0] cache_dict = FCache().covers if basename in cache_dict: cache_dict[basename].append(bean.text) else: cache_dict[basename] = [bean.text] return filename except Exception, e: pass
def update_image(): global _last_mod statbuf = os.stat("./fb.png") mod = statbuf.st_mtime img = None if statbuf.st_size == 0: return True if mod != _last_mod: try: img = Pixbuf.new_from_file("./fb.png") except Exception as e: print(e) return True _last_mod = mod if not img: return True width, height = WIN.get_size() i_height = img.get_height() scalar = i_height / float(height) img = img.scale_simple(int(height / scalar), height, InterpType.BILINEAR) IMG.set_from_pixbuf(img) IMG.queue_draw() return True
def add_pb(model, path, iter, data): try: pb = Pixbuf.new_from_file_at_size( IMGPATH.format(model[iter][3]), 192, 192) except GLib.Error: pb = avatar GLib.idle_add(self.set_value, iter, 4, pb)
def get_pixbuf_for_game(game_slug, icon_type, is_installed): if icon_type in ("banner", "banner_small"): size = BANNER_SIZE if icon_type == "banner" else BANNER_SMALL_SIZE default_icon = DEFAULT_BANNER icon_path = os.path.join(settings.BANNER_PATH, "%s.jpg" % game_slug) elif icon_type == "icon": size = ICON_SIZE default_icon = DEFAULT_ICON icon_path = os.path.join(settings.ICON_PATH, "lutris_%s.png" % game_slug) if not os.path.exists(icon_path): pixbuf = get_default_icon(default_icon, size) else: try: pixbuf = Pixbuf.new_from_file_at_size(icon_path, size[0], size[1]) except GLib.GError: pixbuf = get_default_icon(default_icon, size) if not is_installed: transparent_pixbuf = get_overlay(size).copy() pixbuf.composite(transparent_pixbuf, 0, 0, size[0], size[1], 0, 0, 1, 1, GdkPixbuf.InterpType.NEAREST, 100) return transparent_pixbuf return pixbuf
def main(): global browser global window frontend = frontend_fill() window = gtk.Window() window.connect('destroy', gtk.main_quit) window.set_title("Linux Lite Control Center") window.set_icon(Pixbuf.new_from_file("{0}/litecc.png".format(app_dir))) window.set_size_request(870, 650) # Valtam do we need to resize window? window.set_resizable(False) window.set_position(gtk.WindowPosition.CENTER), browser = webkit.WebView() swindow = gtk.ScrolledWindow() window.add(swindow) swindow.add(browser) window.show_all() browser.connect("navigation-requested", functions) browser.load_html_string(frontend, "file://{0}/frontend/".format(app_dir)) # no right click menu settings = browser.get_settings() settings.set_property('enable-default-context-menu', False) browser.set_settings(settings) # Engage gtk.main()
def load_store(self): missing = self.missing scale = self.scale if self.query_code == 0: sq = Query.get_all_files('archives', self.query_page, self.query_sort, self.query_order, self.query_fn_filter) elif self.query_code == 1: sq = Query.get_1tag_files('archives', self.query_page, self.query_sort, self.query_order, self.query_fn_filter) elif self.query_code == -1: sq = Query.get_notag_files('archives', self.query_page, self.query_sort, self.query_order, self.query_fn_filter) self.clear() for q in sq: try: pb = Pixbuf.new_from_file_at_size(IMGPATH.format(q[0]), scale, scale) except GLib.Error: pb = missing self.append(( *q[:-1], pb, ))
def stop_pressed(self, wdg=None): # Aborting playback cur = self.gst.getnow() self.gst.stop() # Update global vars self.current_song = False self.current_album = False # Update file current_playing = join(self.userconf.datadir, 'current-playing') if exists(current_playing): os_remove(current_playing) # Update user interface self.btn_playpause.set_image(Image.new_from_gicon(ThemedIcon( name='media-playback-start-symbolic'), IconSize.BUTTON)) self.headerbar.props.subtitle = '' default = join(self.functions.datadir, 'image', 'logo_head_big.png') cover_px = Pixbuf.new_from_file_at_scale(default, 20, 20, True) self.player_button_img.set_from_pixbuf(cover_px) self.player_event.set_sensitive(False) self.lyrics_button.set_sensitive(False) self.player_sca.set_sensitive(False) # Do we have to send the signal? if wdg is not None: self.extensions.load_event('OnStopPressed')
def go_Sub(builder,iconview,treepath,SelectedMain): global stage global SubCategoryList global ProgramList global liststore global SelectedSubCat SelectedSubCat = SubCategoryList[treepath.get_indices()[0]] #Clear Icons liststore = iconview.get_model() liststore.clear() ProgramList = db.db_read(SelectedSubCat) for i in ProgramList: pixbuf = Pixbuf.new_from_file_at_size(str(conf.get_entry('DB','dblocation') + db.read_attributes(i)[8]),64,64) liststore.append([pixbuf, i]) iconview.show_all() stage = 'Prog' feedback.status_push(conf.get_entry("Status","menuprogram"))
def open(self, *args): search = Search() links = search.search(self.entry.get_text()) self.grid_helper.refresh() for link in links: url = link.img text = Gtk.Label(link.title) #text.set_size_request(50, 50) text.set_line_wrap(True) response = urllib2.urlopen(url) input_stream = Gio.MemoryInputStream.new_from_data(response.read(), None) pixbuf = Pixbuf.new_from_stream(input_stream, None) image = Gtk.Image() image.set_from_pixbuf(pixbuf) box = Gtk.VBox() box.pack_start(image, False, False, 0) box.pack_start(text, False, False, 0) event_box = Gtk.EventBox() event_box.add(box) event_box.connect("button-press-event", self.serie_clicked, link) self.grid_helper.add_widget(event_box) self.grid_helper.load_widgets() self.window.show_all()
def add_pb(model, path, iter, data): try: pb = Pixbuf.new_from_file_at_size( IMGPATH.format(model[iter][0]), scale, scale) except GLib.Error: pb = missing model.set_value(iter, 8, pb)
def add_pb(model, path, iter, data): try: pb = Pixbuf.new_from_file_at_size( IMGPATH.format(model[iter][3]), size, size) except GLib.Error: pb = avatar model.set_value(iter, 4, pb)
def __init__(self, winParent, show=False): # Retrieve the translators list translators = [] for line in readlines(FILE_TRANSLATORS, False): if ':' in line: line = line.split(':', 1)[1] line = line.replace('(at)', '@').strip() if line not in translators: translators.append(line) # Load the user interface builder = Gtk.Builder() builder.add_from_file(FILE_UI_ABOUT) # Obtain widget references self.dialog = builder.get_object("dialogAbout") # Set various properties self.dialog.set_program_name(APP_NAME) self.dialog.set_version('Version %s' % APP_VERSION) self.dialog.set_comments(APP_DESCRIPTION) self.dialog.set_website(APP_URL) self.dialog.set_copyright(APP_COPYRIGHT) self.dialog.set_authors(['%s <%s>' % (APP_AUTHOR, APP_AUTHOR_EMAIL)]) #self.dialog.set_license_type(Gtk.License.GPL_2_0) self.dialog.set_license('\n'.join(readlines(FILE_LICENSE, True))) self.dialog.set_translator_credits('\n'.join(translators)) # Retrieve the external resources links for line in readlines(FILE_RESOURCES, False): resource_type, resource_url = line.split(':', 1) self.dialog.add_credit_section(resource_type, (resource_url, )) icon_logo = Pixbuf.new_from_file(FILE_ICON) self.dialog.set_logo(icon_logo) self.dialog.set_transient_for(winParent) # Optionally show the dialog if show: self.show()
def functions(view, frame, req, data=None): uri = req.get_uri() lllink, path = uri.split('://', 1) path = path.replace("%20", " ") if lllink == "file": return False elif lllink == "about": about = gtk.AboutDialog() about.set_program_name(appname) about.set_version(appver) about.set_copyright('Copyright Johnathan Jenkins 2016') about.set_wrap_license about.set_license( '''This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''') about.set_authors([ "Johnathan 'ShaggyTwoDope'" + " Jenkins\n<*****@*****.**>\n", "Jerry Bezencon\n<*****@*****.**>\n", "Milos Pavlovic\n<*****@*****.**>\n", "Brian 'DarthLukan' Tomlinson\n<*****@*****.**>\n", "Josh Erickson\n<*****@*****.**>" ]) about.set_comments("Control it all.") about.set_website("https://github.com/nixheads/nixcontrolcenter") about.set_logo(Pixbuf.new_from_file(app_icon)) about.set_transient_for(window) about.run() about.destroy() elif lllink == "admin": subprocess.Popen(path, shell=True, executable='/bin/bash') elif lllink == "script": execute("{0}/scripts/{1}".format(app_dir, path)) elif lllink == "help": webbrowser.open('file:///usr/share/doc/litemanual/index.html') elif lllink == "screenshot": os.system("/bin/bash -c 'scrot -u $HOME/nixccshot.png'") subprocess.Popen(['/bin/bash', '-c', '/usr/share/nixcc/scripts/screenshot']) elif lllink == "report": subprocess.Popen(['/bin/bash', '-c', 'gksudo /usr/scripts/systemreport' ]) elif lllink == "update": subprocess.Popen(['gpk-update-viewer' ]) elif lllink == "refresh": reload() return True
def resizeImage(self, widget, rectangle): if self.settingsManager.resizeImage and self.currentBooru.getCurrentFile(): iWidth = rectangle.width - 15 iHeight = rectangle.height - 15 mpixbuf = Pixbuf.new_from_file_at_scale(self.currentBooru.getCurrentFile(), iWidth, iHeight, True) self.iCurHeight = iHeight self.iCurWidth = iWidth Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT_IDLE, self.GtkSetImage, mpixbuf)
def add_commands(self, commands): command_icon = Pixbuf.new_from_file_at_size( "{base_path}/res/command.svg".format(base_path=os.path.dirname(os.path.realpath(__file__))), 16, 16 ) for name, command in commands.items(): self.append({"type": "command", "name": name, "keyword": command, "command": command, "icon": command_icon})
def orig_zoom(self,widget): self.zoom_actual = 1 pixbuf = Pixbuf.new_from_file(self.v_item_actual) ancho_pixbuf = pixbuf.get_width() alto_pixbuf = pixbuf.get_height() prev_pixbuf = pixbuf.scale_simple(ancho_pixbuf, alto_pixbuf, v_inter) self.image.set_from_pixbuf(prev_pixbuf) self.image.show()
def getThumbnail(path, size): """Gets thumbnail for file at path. The function will try to create one if it is not found. Returns None if this fails.""" defaultIcon = Gtk.IconTheme.get_default().load_icon("gtk-file", size, 0) thumbnailPath = pathToThumbnailPath(path, size) thumbnailers = loadThumbnailers() pixbuf = None try: return Pixbuf.new_from_file_at_size(thumbnailPath, size, size) except: pass if size>128: tsize = 256 else: tsize = 128 try: pixbuf = Pixbuf.new_from_file_at_size(path, tsize, tsize) except: pass if pixbuf is None and guess_type(path)[0] in thumbnailers.keys(): o = '"{}"'.format(thumbnailPath) u = '"file://{}"'.format(path) i = '"{}"'.format(path) s = str(tsize) command = thumbnailers[guess_type(path)[0]] for (pat, sub) in [("%o", o), ("%i", i), ("%u", u), ("%s", s)]: command = re.sub(pat, sub, command) os.system(command) try: pixbuf = Pixbuf.new_from_file_at_size(thumbnailPath, tsize, tsize) except: return defaultIcon if pixbuf is None: return defaultIcon pixbuf.savev(thumbnailPath, "png", [], []) width = pixbuf.get_width() height = pixbuf.get_height() if height > width: width = size * width / height height = size else: height = size * height / width width = size pixbuf = pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR) return pixbuf
def copy_image(f): assert os.path.exists(f), "File does not exist: %s" % f image = Pixbuf.new_from_file(f) atom = Gdk.atom_intern('CLIPBOARD', True) clipboard = Gtk.Clipboard.get(atom) clipboard.set_image(image) clipboard.store() sys.exit(1)
def display_image(self, im): self.imagef = im pb = Pixbuf.new_from_file(im) if pb.get_n_channels()>3: self.mainWin.notify('Sorry, Lucid-GTK doesn\'t currently support images with an alpha channel (such as PNG with transparency).\nIn order to use this image you need to flatten it to RGB in an image editor', color='red') return pb = self.check_im_size(pb) self.mainWin.imContainer.set_size(pb.get_width(),pb.get_height()) self.mainWin.im.set_from_pixbuf(pb)