Python cairo.FORMAT_ARGB32 Examples

The following are 30 code examples of cairo.FORMAT_ARGB32(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cairo , or try the search function .
Example #1
Source File: __init__.py    From GeoVis with MIT License 6 votes vote down vote up
def NewImage(self):
        """
This must be called before doing any rendering.
Note: this replaces any previous image drawn on so be sure to
retrieve the old image before calling it again to avoid losing work
"""
        #first mode
        mode = cairo.FORMAT_ARGB32
        #then other specs
        width = MAPWIDTH
        height = MAPHEIGHT
        background = MAPBACKGROUND
        self.img = cairo.ImageSurface(mode, int(MAPWIDTH), int(MAPHEIGHT))
        self.drawer = cairo.Context(self.img)
        if background:
            backgroundcolor = self.__hex_to_rgb(background)
            self.drawer.set_source_rgb(*backgroundcolor)
            self.drawer.rectangle(0,0,MAPWIDTH,MAPHEIGHT)
            self.drawer.fill() 
Example #2
Source File: backend_cairo.py    From Computable with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # bbox - not currently used
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))

        im.flipud_out()

        rows, cols, buf = im.color_conv (BYTE_FORMAT)
        surface = cairo.ImageSurface.create_for_data (
                      buf, cairo.FORMAT_ARGB32, cols, rows, cols*4)
        ctx = gc.ctx
        y = self.height - y - rows

        ctx.save()
        ctx.set_source_surface (surface, x, y)
        ctx.paint()
        ctx.restore()

        im.flipud_out() 
Example #3
Source File: backend_cairo.py    From ImageFusion with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # bbox - not currently used
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))

        im.flipud_out()

        rows, cols, buf = im.color_conv (BYTE_FORMAT)
        surface = cairo.ImageSurface.create_for_data (
                      buf, cairo.FORMAT_ARGB32, cols, rows, cols*4)
        ctx = gc.ctx
        y = self.height - y - rows

        ctx.save()
        ctx.set_source_surface (surface, x, y)
        if gc.get_alpha() != 1.0:
            ctx.paint_with_alpha(gc.get_alpha())
        else:
            ctx.paint()
        ctx.restore()

        im.flipud_out() 
Example #4
Source File: util.py    From paperwork-backend with GNU General Public License v3.0 6 votes vote down vote up
def image2surface(img):
    """
    Convert a PIL image into a Cairo surface
    """
    if not CAIRO_AVAILABLE:
        raise Exception("Cairo not available(). image2surface() cannot work.")

    # TODO(Jflesch): Python 3 problem
    # cairo.ImageSurface.create_for_data() raises NotImplementedYet ...

    # img.putalpha(256)
    # (width, height) = img.size
    # imgd = img.tobytes('raw', 'BGRA')
    # imga = array.array('B', imgd)
    # stride = width * 4
    #  return cairo.ImageSurface.create_for_data(
    #      imga, cairo.FORMAT_ARGB32, width, height, stride)

    # So we fall back to this method:
    global g_lock
    with g_lock:
        img_io = io.BytesIO()
        img.save(img_io, format="PNG")
        img_io.seek(0)
        return cairo.ImageSurface.create_from_png(img_io) 
Example #5
Source File: svg2png.py    From godot-themes with MIT License 6 votes vote down vote up
def svg2png(svg_file, output_file, scale=1):
    # Get the svg files content
    svg_data = open(svg_file).read()

    # Get the width / height inside of the SVG
    doc = minidom.parseString(svg_data)
    width = [path.getAttribute('width') for path in doc.getElementsByTagName('svg')][0]
    height = [path.getAttribute('height') for path in doc.getElementsByTagName('svg')][0]
    width = int(round(float(re.compile('(\d+\.*\d*)\w*').findall(width)[0])))
    height = int(round(float(re.compile('(\d+\.*\d*)\w*').findall(height)[0])))
    doc.unlink()

    # Create the png
    img = cairo.ImageSurface(
        cairo.FORMAT_ARGB32, width * scale, height * scale)
    ctx = cairo.Context(img)
    ctx.scale(scale, scale)
    handler = rsvg.Handle(None, str(svg_data))
    handler.render_cairo(ctx)
    img.write_to_png(output_file)
    print("{} ==> {}".format(svg_file, output_file)) 
Example #6
Source File: backend_cairo.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # bbox - not currently used
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))

        im.flipud_out()

        rows, cols, buf = im.color_conv (BYTE_FORMAT)
        surface = cairo.ImageSurface.create_for_data (
                      buf, cairo.FORMAT_ARGB32, cols, rows, cols*4)
        ctx = gc.ctx
        y = self.height - y - rows

        ctx.save()
        ctx.set_source_surface (surface, x, y)
        ctx.paint()
        ctx.restore()

        im.flipud_out() 
Example #7
Source File: backend_cairo.py    From neural-network-animation with MIT License 6 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # bbox - not currently used
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))

        im.flipud_out()

        rows, cols, buf = im.color_conv (BYTE_FORMAT)
        surface = cairo.ImageSurface.create_for_data (
                      buf, cairo.FORMAT_ARGB32, cols, rows, cols*4)
        ctx = gc.ctx
        y = self.height - y - rows

        ctx.save()
        ctx.set_source_surface (surface, x, y)
        if gc.get_alpha() != 1.0:
            ctx.paint_with_alpha(gc.get_alpha())
        else:
            ctx.paint()
        ctx.restore()

        im.flipud_out() 
Example #8
Source File: backend_cairo.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def __init__(self, dpi):
        self.dpi = dpi
        self.gc = GraphicsContextCairo(renderer=self)
        self.text_ctx = cairo.Context(
           cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
        self.mathtext_parser = MathTextParser('Cairo')
        RendererBase.__init__(self) 
Example #9
Source File: backend_cairo.py    From ImageFusion with MIT License 5 votes vote down vote up
def __init__(self, dpi):
        """
        """
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))
        self.dpi = dpi
        self.gc = GraphicsContextCairo (renderer=self)
        self.text_ctx = cairo.Context (
           cairo.ImageSurface (cairo.FORMAT_ARGB32,1,1))
        self.mathtext_parser = MathTextParser('Cairo')

        RendererBase.__init__(self) 
Example #10
Source File: backend_cairo.py    From ImageFusion with MIT License 5 votes vote down vote up
def print_png(self, fobj, *args, **kwargs):
        width, height = self.get_width_height()

        renderer = RendererCairo (self.figure.dpi)
        renderer.set_width_height (width, height)
        surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface (surface)

        self.figure.draw (renderer)
        surface.write_to_png (fobj) 
Example #11
Source File: emoji_builder.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def write_format1(self, png):

        import cairo

        img = cairo.ImageSurface.create_from_png(png.stream())
        if img.get_format() != cairo.FORMAT_ARGB32:
            raise Exception("Expected FORMAT_ARGB32, but image has format %d" % img.get_format())

        width = img.get_width()
        height = img.get_height()
        stride = img.get_stride()
        data = img.get_data()

        self.write_smallGlyphMetrics(width, height)

        if sys.byteorder == "little" and stride == width * 4:
            # Sweet.  Data is in desired format, ship it!
            self.write(data)
            return

        # Unexpected stride or endianness, do it the slow way
        offset = 0
        for y in range(height):
            for x in range(width):
                pixel = data[offset + 4 * x: offset + 4 * (x + 1)]
                # Convert to little endian
                pixel = struct.pack("<I", struct.unpack("@I", pixel)[0])
                self.write(pixel)
            offset += stride 
Example #12
Source File: indic_scribe_python2.py    From chamanti_ocr with Apache License 2.0 5 votes vote down vote up
def scribe(text, fontname, ten=10, style=0,
           sz=48, spc=1, movex=10, movey=0, twist=0):
    lines = text.split('\n')
    n_lines = len(lines)
    n_letters = max(len(line) for line in lines)

    size_x = 3 * ten * n_letters + 5 * ten
    size_y = 5 * ten * n_lines + 5 * ten

    # print("Lines: {} Letters:{} Size:{}x{}".format(
    #     n_lines, n_letters, size_x, size_y))

    data = np.zeros((size_y, size_x, 4), dtype=np.uint8)
    surf = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32,
                                              size_x, size_y)
    cr = cairo.Context(surf)
    pc = pangocairo.CairoContext(cr)
    pc.set_antialias(cairo.ANTIALIAS_SUBPIXEL)

    layout = pc.create_layout()
    layout.set_text(text)

    style = styles[style]
    font_style = "{} {} {}".format(fontname, style, (sz * ten)//10)
    layout.set_font_description(pango.FontDescription(font_style))
    layout.set_spacing(spc * 32)

    cr.rectangle(0, 0, size_x, size_y)
    cr.set_source_rgb(1, 1, 1)
    cr.fill()
    cr.translate(ten, 0)
    cr.set_source_rgb(0, 0, 0)

    pc.update_layout(layout)
    pc.show_layout(layout)

    return data[:, :, 0] < 128 
Example #13
Source File: weatherwidget.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def get_surface_from_pixbuf(pixbuf):
    surface = cairo.ImageSurface(
        cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
    micairo = cairo.Context(surface)
    micairo.save()
    Gdk.cairo_set_source_pixbuf(micairo, pixbuf, 0, 0)
    micairo.paint()
    micairo.restore()
    return surface 
Example #14
Source File: weatherwidget.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def get_surface_from_file(filename):
    if os.path.exists(filename):
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
        if pixbuf:
            surface = cairo.ImageSurface(
                cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
            context = cairo.Context(surface)
            Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
            context.paint()
            return surface
    return None 
Example #15
Source File: backend_cairo.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_printed_image_surface(self):
        width, height = self.get_width_height()
        renderer = RendererCairo(self.figure.dpi)
        renderer.set_width_height(width, height)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface(surface)
        self.figure.draw(renderer)
        return surface 
Example #16
Source File: backend_cairo.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def draw_image(self, gc, x, y, im):
        im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1])
        surface = cairo.ImageSurface.create_for_data(
            im.ravel().data, cairo.FORMAT_ARGB32,
            im.shape[1], im.shape[0], im.shape[1] * 4)
        ctx = gc.ctx
        y = self.height - y - im.shape[0]

        ctx.save()
        ctx.set_source_surface(surface, float(x), float(y))
        ctx.paint()
        ctx.restore() 
Example #17
Source File: backend_cairo.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _get_printed_image_surface(self):
        width, height = self.get_width_height()
        renderer = RendererCairo(self.figure.dpi)
        renderer.set_width_height(width, height)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface(surface)
        self.figure.draw(renderer)
        return surface 
Example #18
Source File: backend_cairo.py    From CogAlg with MIT License 5 votes vote down vote up
def __init__(self, dpi):
        self.dpi = dpi
        self.gc = GraphicsContextCairo(renderer=self)
        self.text_ctx = cairo.Context(
           cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
        self.mathtext_parser = MathTextParser('Cairo')
        RendererBase.__init__(self) 
Example #19
Source File: backend_cairo.py    From CogAlg with MIT License 5 votes vote down vote up
def draw_image(self, gc, x, y, im):
        im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1])
        surface = cairo.ImageSurface.create_for_data(
            im.ravel().data, cairo.FORMAT_ARGB32,
            im.shape[1], im.shape[0], im.shape[1] * 4)
        ctx = gc.ctx
        y = self.height - y - im.shape[0]

        ctx.save()
        ctx.set_source_surface(surface, float(x), float(y))
        ctx.paint()
        ctx.restore() 
Example #20
Source File: backend_cairo.py    From CogAlg with MIT License 5 votes vote down vote up
def _get_printed_image_surface(self):
        width, height = self.get_width_height()
        renderer = RendererCairo(self.figure.dpi)
        renderer.set_width_height(width, height)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface(surface)
        self.figure.draw(renderer)
        return surface 
Example #21
Source File: backend_cairo.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def __init__(self, dpi):
        self.dpi = dpi
        self.gc = GraphicsContextCairo(renderer=self)
        self.text_ctx = cairo.Context(
           cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
        self.mathtext_parser = MathTextParser('Cairo')
        RendererBase.__init__(self) 
Example #22
Source File: backend_cairo.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def draw_image(self, gc, x, y, im):
        # bbox - not currently used
        if sys.byteorder == 'little':
            im = im[:, :, (2, 1, 0, 3)]
        else:
            im = im[:, :, (3, 0, 1, 2)]
        if HAS_CAIRO_CFFI:
            # cairocffi tries to use the buffer_info from array.array
            # that we replicate in ArrayWrapper and alternatively falls back
            # on ctypes to get a pointer to the numpy array. This works
            # correctly on a numpy array in python3 but not 2.7. We replicate
            # the array.array functionality here to get cross version support.
            imbuffer = ArrayWrapper(im.flatten())
        else:
            # pycairo uses PyObject_AsWriteBuffer to get a pointer to the
            # numpy array; this works correctly on a regular numpy array but
            # not on a py2 memoryview.
            imbuffer = im.flatten()
        surface = cairo.ImageSurface.create_for_data(
            imbuffer, cairo.FORMAT_ARGB32,
            im.shape[1], im.shape[0], im.shape[1]*4)
        ctx = gc.ctx
        y = self.height - y - im.shape[0]

        ctx.save()
        ctx.set_source_surface(surface, float(x), float(y))
        if gc.get_alpha() != 1.0:
            ctx.paint_with_alpha(gc.get_alpha())
        else:
            ctx.paint()
        ctx.restore() 
Example #23
Source File: backend_cairo.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def print_png(self, fobj, *args, **kwargs):
        width, height = self.get_width_height()

        renderer = RendererCairo(self.figure.dpi)
        renderer.set_width_height(width, height)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface(surface)

        self.figure.draw(renderer)
        surface.write_to_png(fobj) 
Example #24
Source File: backend_gtk3agg.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def on_draw_event(self, widget, ctx):
        """ GtkDrawable draw event, like expose_event in GTK 2.X
        """
        allocation = self.get_allocation()
        w, h = allocation.width, allocation.height

        if not len(self._bbox_queue):
            if self._need_redraw:
                self._render_figure(w, h)
                bbox_queue = [transforms.Bbox([[0, 0], [w, h]])]
            else:
                return
        else:
            bbox_queue = self._bbox_queue

        for bbox in bbox_queue:
            area = self.copy_from_bbox(bbox)
            buf = np.fromstring(area.to_string_argb(), dtype='uint8')

            x = int(bbox.x0)
            y = h - int(bbox.y1)
            width = int(bbox.x1) - int(bbox.x0)
            height = int(bbox.y1) - int(bbox.y0)

            image = cairo.ImageSurface.create_for_data(
                buf, cairo.FORMAT_ARGB32, width, height)
            ctx.set_source_surface(image, x, y)
            ctx.paint()

        if len(self._bbox_queue):
            self._bbox_queue = []

        return False 
Example #25
Source File: backend_cairo.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self, dpi):
        """
        """
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))
        self.dpi = dpi
        self.gc = GraphicsContextCairo (renderer=self)
        self.text_ctx = cairo.Context (
           cairo.ImageSurface (cairo.FORMAT_ARGB32,1,1))
        self.mathtext_parser = MathTextParser('Cairo')

        RendererBase.__init__(self) 
Example #26
Source File: backend_cairo.py    From Computable with MIT License 5 votes vote down vote up
def print_png(self, fobj, *args, **kwargs):
        width, height = self.get_width_height()

        renderer = RendererCairo (self.figure.dpi)
        renderer.set_width_height (width, height)
        surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface (surface)

        self.figure.draw (renderer)
        surface.write_to_png (fobj) 
Example #27
Source File: backend_gtk3agg.py    From Computable with MIT License 5 votes vote down vote up
def on_draw_event(self, widget, ctx):
        """ GtkDrawable draw event, like expose_event in GTK 2.X
        """
        allocation = self.get_allocation()
        w, h = allocation.width, allocation.height

        if not len(self._bbox_queue):
            if self._need_redraw:
                self._render_figure(w, h)
                bbox_queue = [transforms.Bbox([[0, 0], [w, h]])]
            else:
                return
        else:
            bbox_queue = self._bbox_queue

        for bbox in bbox_queue:
            area = self.copy_from_bbox(bbox)
            buf = np.fromstring(area.to_string_argb(), dtype='uint8')

            x = int(bbox.x0)
            y = h - int(bbox.y1)
            width = int(bbox.x1) - int(bbox.x0)
            height = int(bbox.y1) - int(bbox.y0)

            image = cairo.ImageSurface.create_for_data(
                buf, cairo.FORMAT_ARGB32, width, height)
            ctx.set_source_surface(image, x, y)
            ctx.paint()

        if len(self._bbox_queue):
            self._bbox_queue = []

        return False 
Example #28
Source File: backend_cairo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __init__(self, dpi):
        self.dpi = dpi
        self.gc = GraphicsContextCairo(renderer=self)
        self.text_ctx = cairo.Context(
           cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
        self.mathtext_parser = MathTextParser('Cairo')
        RendererBase.__init__(self) 
Example #29
Source File: backend_cairo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def draw_image(self, gc, x, y, im):
        im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1])
        surface = cairo.ImageSurface.create_for_data(
            im.ravel().data, cairo.FORMAT_ARGB32,
            im.shape[1], im.shape[0], im.shape[1] * 4)
        ctx = gc.ctx
        y = self.height - y - im.shape[0]

        ctx.save()
        ctx.set_source_surface(surface, float(x), float(y))
        ctx.paint()
        ctx.restore() 
Example #30
Source File: backend_cairo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_printed_image_surface(self):
        width, height = self.get_width_height()
        renderer = RendererCairo(self.figure.dpi)
        renderer.set_width_height(width, height)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface(surface)
        self.figure.draw(renderer)
        return surface