Example #1
0
def draw_label_cairo(img_path,label,font=False):
    sett = load_settings()
#     im=img_src
#     x = im.size[0]
#     y = im.size[1]
# 
#     im = pil_to_gdk(img_src)
    
#     if font is not False and font is not None:
#         f = ImageFont.truetype(font,f_size)
#     else:
#         f = ImageFont.truetype(sett.font["path"],f_size)
#     
#     im = draw_text_with_halo(im,label,f,0.3,sett.font["color"],sett.font["haloColor"])
    
    im = GdkPixbuf.Pixbuf.new_from_file(img_path)
    x = im.get_width()
    y = im.get_height()
    size = math.sqrt(x*y)
    f_size = (int)((size/60) * sett.font["scale"])
    surface = cairo.ImageSurface(0,x,y)
    
    ct = cairo.Context(surface)
    ct2 = Gdk.CairoContext(ct)
    ct2.set_source_pixbuf(im,0,0)

    
    drawable = GdkPixbuf.render_pixmap_and_mask(alpha_threshold=127)[0]
    
    context = Cairo.Context(im)
    
    return im
Example #2
0
    def __init__(self, icon_size=Gtk.IconSize.DND):
        self.loader =GdkPixbuf.PixbufLoader()
        self.loader.connect("size-prepared", self.on_loader_size_prepared)

        s, w, h = Gtk.IconSize.lookup(icon_size)

        self.surface_size = w
        self.pixbuf_size = w * get_global_scale_factor()
Example #3
0
 def _cv_image_to_pixbuf(self, image):
     """
     Convert cv image (numpy array) to a gtk pixelbuffer
     """
     image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
     return GdkPixbuf.Pixbuf().new_from_data(image.tostring(), 0, False, 8,
                                             image.shape[1], image.shape[0],
                                             image.shape[1] * 3)
Example #4
0
def create_origin_pixbuf_from_url(url):
    f = urllib.urlopen(url)
    data = f.read()
    pbl = GdkPixbuf.PixbufLoader()  #@UndefinedVariable
    pbl.write(data)
    pbuf = pbl.get_pixbuf()
    pbl.close()
    return pbuf
Example #5
0
def download_image_to_pixbuf(url_image):
    opener1 = urllib.request.build_opener()
    page1 = opener1.open(url_image)
    data = page1.read()
    loader = GdkPixbuf.PixbufLoader()
    loader.write(data)
    loader.close()
    pixbuf = loader.get_pixbuf()
    return pixbuf
Example #6
0
    def add_image(self, image):
        gtkimage = Gtk.Image()
        response = urllib2.urlopen(image.small)

        loader = GdkPixbuf.PixbufLoader()
        loader.write(response.read())
        loader.close()
        gtkimage.set_from_pixbuf(loader.get_pixbuf())
        self.image_model.append([gtkimage.get_pixbuf(), image.big])
Example #7
0
def gray_scale_pixBuf(pb, copy):
    pb2 = GdkPixbuf.Pixbuf(
        GdkPixbuf.Colorspace.RGB,
        False,
        8,
        pb.get_width(),
        pb.get_height())
    pb.saturate_and_pixelate(pb2, 0, 0)
    return pb2
Example #8
0
    def get_pixbuf(self, img_encode_buf):

        decode_img_buf = base64.b64decode(img_encode_buf)
        loader = GdkPixbuf.PixbufLoader()
        loader.write(decode_img_buf)
        loader.close()
        pixbuf = loader.get_pixbuf()

        return pixbuf
Example #9
0
def load_pixbuf_from_url(url):
    opener1 = urllib.request.build_opener()
    page1 = opener1.open(url)
    data = page1.read()
    loader = GdkPixbuf.PixbufLoader()
    loader.write(data)
    loader.close()
    pixbuf = loader.get_pixbuf()
    return pixbuf
Example #10
0
    def build_tweet_box(self, tweet):
        # Fetch avatar from URL
        response = urllib.request.urlopen(tweet.user_profile_image_url)
        loader = GdkPixbuf.PixbufLoader()
        loader.write(response.read())
        loader.close()

        # Tweet
        hbox_tweet = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        # Account Avatar
        image_account_avatar = Gtk.Image()
        image_account_avatar.set_from_pixbuf(loader.get_pixbuf())
        image_account_avatar.set_alignment(0.5, 0.0)
        hbox_tweet.pack_start(image_account_avatar, False, True, 8)

        # Tweet Content
        vbox_tweet_content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        # Tweet Header
        hbox_tweet_header = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        label_tweet_header = Gtk.Label()
        label_tweet_header.set_markup('<b>%s</b> ‏<a href="https://twitter.com/%s">@%s</a>' % (tweet.name, tweet.screen_name, tweet.screen_name))
        label_tweet_header.set_alignment(0.0, 0.5)
        hbox_tweet_header.pack_start(label_tweet_header, True, True, 0)
        # Tweet Since
        label_tweet_since = Gtk.Label(tweet.timestamp)
        hbox_tweet_header.pack_start(label_tweet_since, False, True, 0)
        vbox_tweet_content.pack_start(hbox_tweet_header, False, True, 0)

        # Tweet message
        label_tweet_text = Gtk.Label(tweet.text)
        label_tweet_text.set_line_wrap(True)
        label_tweet_text.set_alignment(0.0, 0.5)
        label_tweet_text.set_selectable(True)
        vbox_tweet_content.pack_start(label_tweet_text, False, True, 4)

        # Tweet Toolbox
        hbox_tweet_toolbox = Gtk.Box(spacing=12, orientation=Gtk.Orientation.HORIZONTAL)
        # Reply
        label_tweet_reply = Gtk.Label()
        label_tweet_reply.set_markup('<a href="https://twitter.com/intent/tweet?in_reply_to_status_id=%s">Reply</a>' % tweet.id)
        hbox_tweet_toolbox.pack_start(label_tweet_reply, False, True, 0)
        # Retweet
        label_tweet_retweet = Gtk.Label()
        label_tweet_retweet.set_markup('<a href="https://twitter.com/intent/retweet?tweet_id=%s">Retweet</a>' % tweet.id)
        hbox_tweet_toolbox.pack_start(label_tweet_retweet, False, True, 0)
        # Favorite
        label_tweet_favorite = Gtk.Label()
        label_tweet_favorite.set_markup('<a href="https://twitter.com/intent/favorite?tweet_id=%s">Favorite</a>' % tweet.id)
        hbox_tweet_toolbox.pack_start(label_tweet_favorite, False, True, 0)

        vbox_tweet_content.pack_start(hbox_tweet_toolbox, False, True, 8)

        hbox_tweet.pack_start(vbox_tweet_content, False, True, 0)

        hbox_tweet.show_all()
        return hbox_tweet
Example #11
0
    def __init__(self, font_name):
        super(Gtk.Image, self).__init__()

        loader = GdkPixbuf.PixbufLoader()
        loader.write(self._FONT_ICON.encode())
        loader.close()
        pixbuf = loader.get_pixbuf()
        self.set_from_pixbuf(pixbuf)
        self.show()
Example #12
0
 def __dl_thumb_cb(self, session, msg, callback):
     pbl = GdkPixbuf.PixbufLoader()
     try:
         pbl.write(msg.props.response_body.flatten().get_data())
     except GLib.Error as e:
         print(e)
         pass
     pbl.close()
     callback(pbl.get_pixbuf())
Example #13
0
    def ShowUserInfo(self, descr, has_pic, pic, totalupl, queuesize,
                     slotsavail, uploadallowed):

        self.conn = None
        self._descr = descr
        self.image_pixbuf = None
        self.descr.get_buffer().set_text("")

        AppendLine(self.descr,
                   descr,
                   self.tag_local,
                   showstamp=False,
                   scroll=False)

        self.uploads.set_text(_("Total uploads allowed: %i") % totalupl)
        self.queuesize.set_text(_("Queue size: %i") % queuesize)

        if slotsavail:
            slots = _("Yes")
        else:
            slots = _("No")

        self.slotsavail.set_text(_("Slots free: %s") % slots)

        if uploadallowed == 0:
            allowed = _("No one")
        elif uploadallowed == 1:
            allowed = _("Everyone")
        elif uploadallowed == 2:
            allowed = _("Users in list")
        elif uploadallowed == 3:
            allowed = _("Trusted Users")
        else:
            allowed = _("unknown")

        self.AcceptUploads.set_text(_("%s") % allowed)

        if has_pic and pic is not None:
            try:
                import gc
                loader = GdkPixbuf.PixbufLoader()
                loader.write(pic)
                loader.close()
                self.image_pixbuf = loader.get_pixbuf()
                self.image.set_from_pixbuf(self.image_pixbuf)
                del pic, loader
                gc.collect()
                self.actual_zoom = 0
                self.SavePicture.set_sensitive(True)
            except TypeError:
                name = tempfile.mktemp()
                f = open(name, "w")
                f.write(pic)
                f.close()
                self.image.set_from_file(name)
                os.remove(name)
Example #14
0
def load_image_max_size(filename, w, h):
    pl = GdkPixbuf.PixbufLoader()
    pl.connect("size-prepared", _set_size, w, h)
    try:
        with open(filename, "rb") as f:
            shutil.copyfileobj(f, pl)
        pl.close()
    except (GLib.GError, EnvironmentError) as exc:
        raise OperationError(exc)
    return pl.get_pixbuf()
Example #15
0
    def update(self, state: pyspiel.State):
        fen = str(state)
        board = chess.Board(fen)
        svg = chess.svg.board(board)

        loader = GdkPixbuf.PixbufLoader()
        loader.write(svg.encode())
        loader.close()
        pixbuf = loader.get_pixbuf()
        self.image.set_from_pixbuf(pixbuf)
def get_image_pixbuf(image_data=None, width=50, height=50):
    assert image_data is not None
    loader = GdkPixbuf.PixbufLoader()
    loader.write(image_data)
    loader.close()
    pixbuf = loader.get_pixbuf()
    if (pixbuf.get_width() > width or pixbuf.get_height() > height):
        pixbuf = pixbuf.scale_simple(width, height,
                                     GdkPixbuf.InterpType.BILINEAR)
    return pixbuf
 def image2pixbuf(self, img):
     file1 = StringIO()
     img.save(file1, "ppm")
     contents = file1.getvalue()
     file1.close()
     loader = GdkPixbuf.PixbufLoader()
     loader.write(contents)
     pixbuf = loader.get_pixbuf()
     loader.close()
     return pixbuf
Example #18
0
    def handle_img(self, tag, attr):
        dattr = dict(attr)
        src = dattr.get('src')
        data = None
        alt = ""
        if src:
            data, msg = self.url_load(src)
            if data is None:
                logger.error("Error loading %s: %s", src, msg)
                alt = dattr.get('alt', 'Broken image')
            else:
                alt = dattr.get('alt', '')

        # Process width and height attributes
        attrwidth = dattr.get('width')
        attrheight = dattr.get('height')
        # Note: attrwidth and attrheight are strings (possibly empty)

        if data is not None:
            # Caveat: GdkPixbuf is known not to be safe to load images
            # from network... this program is now potentially hackable
            # ;)
            loader = GdkPixbuf.PixbufLoader()

            def set_size(pixbuf, width, height):
                if attrwidth and attrheight:
                    # Both are specified. Simply use them.
                    width, height = attrwidth, attrheight
                elif attrwidth:
                    # Only width is specified.
                    height = int(int(attrwidth) * height / width)
                    width = int(attrwidth)
                elif attrheight:
                    width = int(attrheight) * width / height
                    height = int(attrheight)
                loader.set_size(int(width), int(height))

            if attrwidth or attrheight:
                loader.connect('size-prepared', set_size)
            try:
                loader.write(data)
                loader.close()
                pixbuf = loader.get_pixbuf()
            except GObject.GError:
                pixbuf = None
        else:
            pixbuf = None

        if pixbuf is None:
            pixbuf = GdkPixbuf.Pixbuf.new_from_xpm_data(broken_xpm)
        pixbuf._tag = tag
        pixbuf._attr = attr
        pixbuf._alt = alt
        self.insert_pixbuf(pixbuf)
Example #19
0
    def set_image(self,bytes_image):

        loader = GdkPixbuf.PixbufLoader()
        loader.write(bytes_image.getbuffer())
        loader.close()

        self.current_pixbuf = loader.get_pixbuf()
         
        pixbuf = self.scale_pixbuf(self.current_pixbuf)

        self.set_from_pixbuf(pixbuf)
Example #20
0
def load_pixbuf_data(imgdata):
    ''' Loads a pixbuf from the data passed in <imgdata>. '''
    try:
        with Image.open(BytesIO(imgdata)) as im:
            return pil_to_pixbuf(im, keep_orientation=True)
    except:
        pass
    loader = GdkPixbuf.PixbufLoader()
    loader.write(imgdata)
    loader.close()
    return loader.get_pixbuf()
Example #21
0
        def loader_cb(data):
            if data and len(data) >= 1000:
                l = GdkPixbuf.PixbufLoader()
                l.write(data)
                l.close()
                pixbuf = l.get_pixbuf()
            else:
                pixbuf = None

            self.art_db.cancel_get_pixbuf(entry)
            self.on_get_pixbuf_completed(entry, pixbuf, uri, None, None)
Example #22
0
 def _pixbuf_from_stream(fp, feedback_cb=None):
     loader = GdkPixbuf.PixbufLoader()
     while True:
         if feedback_cb is not None:
             feedback_cb()
         buf = fp.read(LOAD_CHUNK_SIZE)
         if buf == '':
             break
         loader.write(buf)
     loader.close()
     return loader.get_pixbuf()
Example #23
0
    def __init__(self, app):
        """Set default values for attributes."""
        super(Image, self).__init__()
        self._app = app

        # Settings and defaults
        self.fit_image = "overzoom"
        self._pixbuf_iter = GdkPixbuf.PixbufAnimationIter()
        self._pixbuf_original = GdkPixbuf.Pixbuf()
        self.zoom_percent = 1
        self._identifier = 0
        self._size = (1, 1)
        self._timer_id = 0
        self._faulty_image = False

        # Connect signals
        self._app["transform"].connect("changed", self._on_image_changed)
        self._app["commandline"].search.connect("search-completed",
                                                self._on_search_completed)
        settings.connect("changed", self._on_settings_changed)
Example #24
0
 def tile(self, pathtofile, char):
     if pathtofile == char:
         thisTile = Gtk.Label(char)
     else:
         thisTile = Gtk.Image()
         if pathtofile == '':
             thisTile.set_size_request(32, 32)
         else:
             pixbuf = GdkPixbuf.Pixbuf().new_from_file_at_scale(
                 pathtofile, 32, 32, True)
             thisTile.set_from_pixbuf(pixbuf)
     return thisTile
Example #25
0
    def __drag_begin_cb(self, widget, context):
        # Drag and Drop
        pixbuf = GdkPixbuf.Pixbuf(GdkPixbuf.Colorspace.RGB, True, 8,
                                  style.SMALL_ICON_SIZE, style.SMALL_ICON_SIZE)

        red = self._color.red / 257
        green = self._color.green / 257
        blue = self._color.blue / 257

        pixbuf.fill(red << 24 + green << 16 + blue << 8 + 0xff)

        context.set_icon_pixbuf(pixbuf)
Example #26
0
def get_album_art(url, *extra):
    try:
        with urllib.request.urlopen(url) as f:
            image = f.read()
    except urllib.error.HTTPError:
        logging.warn('Invalid image url received')
        return (None, ) + extra

    with contextlib.closing(GdkPixbuf.PixbufLoader()) as loader:
        loader.set_size(ALBUM_ART_SIZE, ALBUM_ART_SIZE)
        loader.write(image)
        return (loader.get_pixbuf(), ) + extra
Example #27
0
def pixbuf_from_stream(fp, feedback_cb=None):
    """Extract and return a GdkPixbuf from file-like object"""
    loader = GdkPixbuf.PixbufLoader()
    while True:
        if feedback_cb is not None:
            feedback_cb()
        buf = fp.read(LOAD_CHUNK_SIZE)
        if buf == '':
            break
        loader.write(buf)
    loader.close()
    return loader.get_pixbuf()
Example #28
0
def about_dialog(_):
    """Set-up About Dialog"""
    widget = Gtk.AboutDialog()
    widget.set_license_type(Gtk.License.MIT_X11)
    widget.set_authors(["Binyamin Green https://binyam.in"])
    widget.set_version("1.0.0")
    widget.set_website("https://github.com/b3u/pyconvert/")
    widget.set_website_label("Source Code")
    widget.set_logo(GdkPixbuf.Pixbuf().new_from_file_at_size(
        'logo.svg', 48, 48))
    widget.connect("response", lambda w, _: w.close())
    widget.run()
Example #29
0
def pil_to_pixbuf(pil_image):
    if pil_image.mode != "RGB":  # Fix IOError: cannot write mode P as PPM
        pil_image = pil_image.convert("RGB")
    buff = io.StringIO()
    pil_image.save(buff, "ppm")
    contents = buff.getvalue()
    buff.close()
    loader = GdkPixbuf.PixbufLoader()
    loader.write(contents)
    pixbuf = loader.get_pixbuf()
    loader.close()
    return pixbuf
Example #30
0
 def image_data_load(self, data):
     if data and len(data) >= 1000:
         try:
             l = GdkPixbuf.PixbufLoader()
             l.write(data)
             l.close()
             return l.get_pixbuf()
         except gobject.GError, e:
             print "error reading image: %s" % str(e)
             import sys
             sys.excepthook(*sys.exc_info())
             pass
Example #31
0
 def loader_cb_busted(data):
     if data and len(data) >= 1000:
         pbl = GdkPixbuf.PixbufLoader()
         try:
             if pbl.write(data, len(data)) and pbl.close():
                 pixbuf = pbl.get_pixbuf()
                 if pixbuf:
                     self.art_db.cancel_get_pixbuf(entry)
                     self.on_get_pixbuf_completed(
                         entry, pixbuf, uri, None, None)
         except GError:
             pass
Example #32
0
    def __init__(self, icon):
        """ Animate a gtk.Image

        Keywords:
        icon: pass either:
              - None - creates empty image with self.SIZE
              - string - for a static icon
              - string - for a image with multiple sub icons
              - list of string pathes
              - a gtk.gdk.Pixbuf if you require a static image
        """
        super(AnimatedImage, self).__init__()
        self._progressN = 0
        if icon is None:
            icon = GdkPixbuf.new(GdkPixbuf.Colorspace.RGB, True, 8, 1, 1)
            icon.fill(0)
        if isinstance(icon, list):
            self.images = []
            for f in icon:
                self.images.append(GdkPixbuf.Pixbuf.new_from_file(f))
        elif isinstance(icon, GdkPixbuf.Pixbuf):
            self.images = [icon]
            self.set_from_pixbuf(icon)
        elif isinstance(icon, str):
            self._imagefiles = icon
            self.images = []
            if not self._imagefiles:
                raise IOError, "no images for the animation found in '%s'" % icon
            # construct self.images list
            pixbuf_orig = GdkPixbuf.Pixbuf.new_from_file(icon)
            pixbuf_buffer = pixbuf_orig.copy()
            x = 0
            y = 0
            for f in range((pixbuf_orig.get_width() / self.SIZE) *
                           (pixbuf_orig.get_height() / self.SIZE)):
                pixbuf_orig.copy_area(x, y, self.SIZE, self.SIZE, pixbuf_buffer, 0, 0)
                self.images.append(pixbuf_buffer)
                if x == (pixbuf_orig.get_width() - self.SIZE):
                    x = 0
                    y += self.SIZE
                else:
                    x += self.SIZE

            self.set_from_pixbuf(self.images[self._progressN])
            self.connect("show", self.start)
            self.connect("hide", self.stop)
        else:
            raise IOError, "need a str, list or a pixbuf"
Example #33
0
 def on_transactions_changed(self, backend, total_transactions):
     LOG.debug("on_transactions_changed '%s'" % total_transactions)
     pending = len(total_transactions)
     if pending > 0:
         for row in self:
             if row[self.COL_ACTION] == ViewPages.PENDING:
                 row[self.COL_BUBBLE_TEXT] = str(pending)
                 break
         else:
             icon = GdkPixbuf.new_from_file(self.ANIMATION_PATH)
             #~ icon.start()
             self.append(None, [icon, _("In Progress..."),
                          ViewPages.PENDING, None, str(pending)])
     else:
         for (i, row) in enumerate(self):
             if row[self.COL_ACTION] == ViewPages.PENDING:
                 del self[(i,)]
Example #34
0
    def show_about_dlg(self, parent):
        dlg = Gtk.AboutDialog()
        dlg.set_type_hint(Gdk.WindowTypeHint.DIALOG)
        dlg.set_modal(True)
        dlg.set_transient_for(parent)
        dlg.set_default_response(Gtk.ResponseType.CLOSE)
        dlg.connect('delete-event', lambda w,*a: w.hide() or True)
        dlg.connect('response', lambda w,*a: w.hide() or True)
        try:
            dlg.set_program_name("Othman")
        except:
            pass
        dlg.set_name(_('Othman Quran Browser'))
        #dlg.set_version(version)
        dlg.set_copyright("Copyright © 2008-2010 Muayyad Saleh Alsadi <*****@*****.**>")
        dlg.set_comments(_("Electronic Mus-haf"))
        dlg.set_license("""
        Released under terms of Waqf Public License.
        This program is free software; you can redistribute it and/or modify
        it under the terms of the latest version Waqf Public License as
        published by Ojuba.org.

        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.

        The Latest version of the license can be found on
        "http://waqf.ojuba.org/"

        """)
        dlg.set_website("http://othman.ojuba.org/")
        dlg.set_website_label("http://othman.ojuba.org")
        dlg.set_authors(["Muayyad Saleh Alsadi <*****@*****.**>"])
        dlg.set_translator_credits(_("translator-credits"))
        fn = os.path.join(self.data_dir, "quran-kareem.svg")
        try:
            logo = GdkPixbuf.Pixbuf.new_from_file_at_size(fn, 128, 128)
        except:
            fn = os.path.join(self.data_dir, "quran-kareem.png")
            logo = GdkPixbuf.pixbuf_new_from_file(fn)
        dlg.set_logo(logo)
        #dlg.set_logo_icon_name('Othman')
        dlg.run()
        dlg.destroy()
Example #35
0
    def to_gtk_buff(self):
        """
        Converts image to gtkImage and returns it

        Arguments:
        - self: The main object pointer.
        """

        img = self.__image

        if "as_numpy_array" in dir(img):
            buff = GdkPixbuf.new_from_array(img.as_numpy_array(),
                                                 GdkPixbuf.Colorspace.RGB,
                                                 img.depth)
        else:
            buff = GdkPixbuf.Pixbuf.new_from_data(img.tostring(),
                                                GdkPixbuf.Colorspace.RGB,
                                                False,                      # has alpha channel
                                                8, #depth
                                                img.shape[1], #width
                                                img.shape[0], #height
                                                img.shape[1]*img.shape[2],
                                                None, None)
        return buff