How to use the cairocffi.ImageSurface.create_from_png function in cairocffi

To help you get started, we’ve selected a few cairocffi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Kozea / CairoSVG / cairosvg / test_api.py View on Github external
svg_filename = file_object.name
        file_object.close()

        assert test_main(['--help'], exit_=True).startswith(b'usage: ')
        assert test_main(['--version'], exit_=True).strip() == (
            VERSION.encode('ascii'))

        assert test_main([svg_filename]) == expected_pdf
        assert test_main([svg_filename, '-d', '96', '-f', 'pdf']) == (
            expected_pdf)
        assert test_main([svg_filename, '-f', 'png']) == expected_png
        assert test_main(['-'], input_=svg_filename) == expected_pdf

        # Test DPI
        output = test_main([svg_filename, '-d', '10', '-f', 'png'], full=True)
        image = cairo.ImageSurface.create_from_png(io.BytesIO(output))
        assert image.get_width() == 40
        assert image.get_height() == 50

        temp = tempfile.mkdtemp()
        try:
            temp_1 = os.path.join(temp, 'result_1')
            # Default to PDF
            assert not test_main([svg_filename, '-o', temp_1])
            assert read_file(temp_1)[:100] == expected_pdf

            temp_2 = os.path.join(temp, 'result_2.png')
            # Guess from the file extension
            assert not test_main([svg_filename, '-o', temp_2])
            assert read_file(temp_2)[:100] == expected_png

            temp_3 = os.path.join(temp, 'result_3.png')
github Kozea / cairocffi / cairocffi / test_cairo.py View on Github external
assert written_png_bytes.startswith(png_magic_number)
        open(filename, 'wb').close()
        with open(filename, 'rb') as fd:
            assert fd.read() == b''
        surface.write_to_png(filename_bytes)
        with open(filename, 'rb') as fd:
            assert fd.read() == written_png_bytes
        file_obj = io.BytesIO()
        surface.write_to_png(file_obj)
        assert file_obj.getvalue() == written_png_bytes
        assert surface.write_to_png() == written_png_bytes

        with open(filename, 'wb') as fd:
            fd.write(png_bytes)
        for source in [io.BytesIO(png_bytes), filename, filename_bytes]:
            surface = ImageSurface.create_from_png(source)
            assert surface.get_format() == cairocffi.FORMAT_ARGB32
            assert surface.get_width() == 1
            assert surface.get_height() == 1
            assert surface.get_stride() == 4
            assert surface.get_data()[:] == pixel(b'\xcc\x32\x6e\x97')

    with pytest.raises(IOError):
        # Truncated input
        surface = ImageSurface.create_from_png(io.BytesIO(png_bytes[:30]))
    with pytest.raises(IOError):
        surface = ImageSurface.create_from_png(io.BytesIO(b''))
github koonimaru / DeepGMAP / deepgmap / post_train_tools / kernel_visualizer.py View on Github external
cr.stroke()
                linked3.add(l)
            if len(linked3)==0:
                sys.exit("no link was found")
            linked_conv.append(linked3)
        prev_y1=[]
        for i in sorted(linked_conv[-1]):
            x1, y1=coordinates["hidden1"][i]
            im = Image.open(png_list[i])
            xwidth=128
            ywidth=int(im.size[1]*xwidth/float(im.size[0]))
            im=im.resize([xwidth, ywidth], Image.ANTIALIAS)
            _buffer = StringIO.StringIO()
            im.save(_buffer, format="PNG",quality=100)
            _buffer.seek(0)
            png_image=cairo.ImageSurface.create_from_png(_buffer)
            if not len(prev_y1)==0 and (y1-prev_y1[-1][1])<(ywidth-10) and prev_y1[-1][0]==0:
                a=xwidth-20
            else:
                a=0
            cr.set_source_surface(png_image, lateral_lim-xwidth-a+10, y1-ywidth/2)
            cr.paint()
            prev_y1.append([a, y1])
        
        cr.show_page()
github Kozea / cairocffi / cairocffi / pixbuf.py View on Github external
def pixbuf_to_cairo_png(pixbuf):
    """Convert from PixBuf to ImageSurface, by going through the PNG format.

    This method is 10~30x slower than GDK but always works.

    """
    buffer_pointer = ffi.new('gchar **')
    buffer_size = ffi.new('gsize *')
    error = ffi.new('GError **')
    handle_g_error(error, pixbuf.save_to_buffer(
        buffer_pointer, buffer_size, ffi.new('char[]', b'png'), error,
        ffi.new('char[]', b'compression'), ffi.new('char[]', b'0'),
        ffi.NULL))
    png_bytes = ffi.buffer(buffer_pointer[0], buffer_size[0])
    return ImageSurface.create_from_png(BytesIO(png_bytes))
github fogleman / AdventOfCode2018 / extra / 17-cairo.py View on Github external
from collections import deque
import cairocffi as cairo
import fileinput
import re

dirt = cairo.ImageSurface.create_from_png('tiles/12/dirt.png')
grass = cairo.ImageSurface.create_from_png('tiles/12/grass.png')
stone = cairo.ImageSurface.create_from_png('tiles/12/stone.png')
water = cairo.ImageSurface.create_from_png('tiles/12/water.png')
water_high = cairo.ImageSurface.create_from_png('tiles/12/water-high.png')
water_low = cairo.ImageSurface.create_from_png('tiles/12/water-low.png')

class Model:
    def __init__(self, lines):
        self.clay = set()
        self.still = set()
        self.flowing = set()
        self.still_t = {}
        self.flowing_t = {}
        for line in lines:
            a, b0, b1 = map(int, re.findall(r'\d+', line))
            for b in range(b0, b1 + 1):
                self.clay.add((a, b) if line[0] == 'x' else (b, a))
        self.x0 = min(x for x, y in self.clay)
        self.x1 = max(x for x, y in self.clay)
        self.y0 = min(y for x, y in self.clay)
        self.y1 = max(y for x, y in self.clay)
github qtile / qtile / libqtile / widget / currentlayout.py View on Github external
def _setup_images(self):
        """
        Loads layout icons.
        """
        for layout_name in self._get_layout_names():
            icon_file_path = self.find_icon_file_path(layout_name)
            if icon_file_path is None:
                logger.warning('No icon found for layout "{}"'.format(layout_name))
                icon_file_path = self.find_icon_file_path('unknown')

            try:
                img = cairocffi.ImageSurface.create_from_png(icon_file_path)
            except (cairocffi.Error, IOError) as e:
                # Icon file is guaranteed to exist at this point.
                # If this exception happens, it means the icon file contains
                # an invalid image or is not readable.
                self.icons_loaded = False
                logger.exception(
                    'Failed to load icon from file "{}", '
                    'error was: {}'.format(icon_file_path, e.message)
                )
                return

            input_width = img.get_width()
            input_height = img.get_height()

            sp = input_height / (self.bar.height - 1)
github fogleman / AdventOfCode2018 / extra / 17-cairo.py View on Github external
from collections import deque
import cairocffi as cairo
import fileinput
import re

dirt = cairo.ImageSurface.create_from_png('tiles/12/dirt.png')
grass = cairo.ImageSurface.create_from_png('tiles/12/grass.png')
stone = cairo.ImageSurface.create_from_png('tiles/12/stone.png')
water = cairo.ImageSurface.create_from_png('tiles/12/water.png')
water_high = cairo.ImageSurface.create_from_png('tiles/12/water-high.png')
water_low = cairo.ImageSurface.create_from_png('tiles/12/water-low.png')

class Model:
    def __init__(self, lines):
        self.clay = set()
        self.still = set()
        self.flowing = set()
        self.still_t = {}
        self.flowing_t = {}
        for line in lines:
            a, b0, b1 = map(int, re.findall(r'\d+', line))
            for b in range(b0, b1 + 1):
github Kozea / WeasyPrint / weasyprint / images.py View on Github external
with fetch(url_fetcher, url) as result:
            if 'string' in result:
                string = result['string']
            else:
                string = result['file_obj'].read()
            mime_type = forced_mime_type or result['mime_type']
            if mime_type == 'image/svg+xml':
                # No fallback for XML-based mimetypes as defined by MIME
                # Sniffing Standard, see https://mimesniff.spec.whatwg.org/
                image = SVGImage(string, url, url_fetcher)
            else:
                # Try to rely on given mimetype
                try:
                    if mime_type == 'image/png':
                        try:
                            surface = cairocffi.ImageSurface.create_from_png(
                                BytesIO(string))
                        except Exception as exception:
                            raise ImageLoadingError.from_exception(exception)
                        else:
                            image = RasterImage(surface)
                    else:
                        image = None
                except ImageLoadingError:
                    image = None

                # Relying on mimetype didn't work, give the image to GDK-Pixbuf
                if not image:
                    if pixbuf is None:
                        raise ImageLoadingError(
                            'Could not load GDK-Pixbuf. PNG and SVG are '
                            'the only image formats available.')
github datamade / lascaux / pdfer / core.py View on Github external
offset_y = (center_point_y - float(center_tile_y)) - 50

    outp_image = cv2.imread(outp_name, -1)
    pixels_up, pixels_across, channels = outp_image.shape
    center_x, center_y = (pixels_across / 2) + offset_x, (pixels_up / 2) + offset_y
    start_y, end_y = center_y - (page_height / 2), center_y + (page_height / 2)
    start_x, end_x = center_x - (page_width / 2), center_x + (page_width / 2)

    cv2.imwrite(outp_name, outp_image[math.floor(start_y):math.ceil(end_y), math.floor(start_x):math.ceil(end_x)])

    if output == 'pdf':
        outp_file_name = outp_name.rstrip('.png') + '.pdf'

        pdf = cairo.PDFSurface(outp_file_name, page_width, page_height)
        ctx = cairo.Context(pdf)
        image = cairo.ImageSurface.create_from_png(outp_name)
        ctx.set_source_surface(image)
        ctx.paint()
        pdf.finish()
    elif output == 'jpeg':
        outp_file_name = outp_name.rstrip('.png') + '.jpg'
        jpeg = cv2.cvtColor(cv2.imread(outp_name, -1), cv2.COLOR_RGBA2RGB)
        cv2.imwrite(outp_file_name, jpeg)
    return outp_file_name