logo
Tags down

shadow

How to install cairo and rsvg for python


By : surya
Date : October 16 2020, 06:10 AM
This might help you
Edit: Ok, so pip won't work for installing pycairo. Found that out. And the other options haven't worked for me either. I am about to be away from my computer, but I'll give you some of the things I found.
code :
#some code to give rsvg.render_cairo(ctx) ability
#on windows.
import os
try:
    import rsvg
    WINDOWS=False
except ImportError:
    print"Warning, could not import 'rsvg'"
    if os.name == 'nt':
        print "Detected windows, creating rsvg."
        #some workarounds for windows

        from ctypes import *

        l=CDLL('librsvg-2-2.dll')
        g=CDLL('libgobject-2.0-0.dll')
        g.g_type_init()

        class rsvgHandle():
            class RsvgDimensionData(Structure):
                _fields_ = [("width", c_int),
                            ("height", c_int),
                            ("em",c_double),
                            ("ex",c_double)]

            class PycairoContext(Structure):
                _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__),
                            ("ctx", c_void_p),
                            ("base", c_void_p)]

            def __init__(self, path):
                self.path = path
                error = ''
                self.handle = l.rsvg_handle_new_from_file(self.path,error)


            def get_dimension_data(self):
                svgDim = self.RsvgDimensionData()
                l.rsvg_handle_get_dimensions(self.handle,byref(svgDim))
                return (svgDim.width,svgDim.height)

            def render_cairo(self, ctx):
                ctx.save()
                z = self.PycairoContext.from_address(id(ctx))
                l.rsvg_handle_render_cairo(self.handle, z.ctx)
                ctx.restore()



        class rsvgClass():
            def Handle(self,file):
                return rsvgHandle(file)
rC = rsvgClass()
h = rC.Handle("YOUR-FILE-HERE.svg")
s = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
ctx = cairo.Context(s)
h.render_cairo(ctx)


Share : facebook icon twitter icon

Text along the curves absence after convertion from svg to png using python+cairo+rsvg


By : Perte Anžu
Date : March 29 2020, 07:55 AM
I wish did fix the issue. textPath doesn't seem to be supported in librsvg, see e.g http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=577844

wrong color channels, pygame cairo rsvg drawing


By : jainrk
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Indeed - the byte order for each channel is different from cairo to pygame. You can either juggle with the array before converting it to a string, to post the data in the correct order for pygame (you'd have to swap the green and blue data for each pixel) - or use an aditional dependency: Python's PIL, to properly handle the different data at native speeds.
There is an snippet for that in pygame's site:
code :
def bgra_surf_to_rgba_string(cairo_surface):
    # We use PIL to do this
    img = Image.frombuffer(
        'RGBA', (cairo_surface.get_width(),
                 cairo_surface.get_height()),
        cairo_surface.get_data(), 'raw', 'BGRA', 0, 1)
    return img.tostring('raw', 'RGBA', 0, 1)

 ...
 # On little-endian machines (and perhaps big-endian, who knows?),
# Cairo's ARGB format becomes a BGRA format. PyGame does not accept
# BGRA, but it does accept RGBA, which is why we have to convert the
# surface data. You can check what endian-type you have by printing
# out sys.byteorder
data_string = bgra_surf_to_rgba_string(cairo_surface)

# Create PyGame surface
pygame_surface = pygame.image.frombuffer(
    data_string, (width, height), 'RGBA')
def draw_svg(self):
    """draw .svg to pygame Surface"""
    svg = rsvg.Handle(file= os.path.join('data', self.filename))        
    dim = svg.get_dimension_data()
    self.width , self.height = dim[0], dim[1]

    data = array.array('c', chr(0) * self.width * self.height * 4 )
    cairo_surf= cairo.ImageSurface.create_for_data( data,
        cairo.FORMAT_ARGB32, self.width, self.height, self.width * 4 )
    ctx = cairo.Context(cairo_surf)

    blue = data[1::4]
    green = data[3::4]
    data[1::4] = green
    data[3::4] = blue
    svg.render_cairo(ctx)
    self.image = pygame.image.frombuffer(data.tostring(), (self.width,self.height), "ARGB")

C++ Cairo + RSVG - Set SVG colour when drawing


By : Eliandro Lima
Date : March 29 2020, 07:55 AM
Hope that helps cairo_mask and cairo_mask_surface can use the alpha channel of another surface as the mask for a drawing operation. The following example uses this to "draw things" with a specific alpha level.
I also added the necessary things to make this a self-contained example and got rid of the unnecessary cairo_image_surface_create_for_data.
code :
#include <cairo.h>
#include <librsvg/rsvg.h>
#include <math.h>

#define gulPanelW 800
#define gulPanelH 480

int main()
{
    //Display buffer and Canvas
    cairo_surface_t *surface;

    surface = cairo_image_surface_create (CAIRO_FORMAT_A8, gulPanelW, gulPanelH);
    cairo_t *cr = cairo_create (surface);

    cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);

    //Flame Surface and SVG Handle
    RsvgHandle* flame_handle;
    flame_handle = rsvg_handle_new_from_file("flame.svg", 0);

    //Set canvas background to grey
    cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, 0.5);
    cairo_paint (cr);

    //Add initial data and output
    cairo_select_font_face (cr, "serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
    cairo_set_font_size (cr, 48.0);
    cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, 0.0);
    cairo_move_to (cr, 700.0, 105.0);
    cairo_rotate(cr, (M_PI/2.0));
    cairo_show_text (cr, "Temperature");
    cairo_rotate(cr, -(M_PI/2.0));

    cairo_select_font_face (cr, "serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
    cairo_set_font_size (cr, 200.0);
    cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, 0.0);
    cairo_move_to (cr, 540.0, 34.0);
    cairo_rotate(cr, (M_PI/2.0));
    cairo_show_text (cr, "19.4");
    cairo_rotate(cr, -(M_PI/2.0));

    // Draw the flame icon to a temporary surface
    cairo_save (cr);
    cairo_translate (cr, 476.0, 200.0);
    cairo_scale (cr, 0.07, 0.07);
    cairo_rotate(cr, (M_PI/2.0));
    cairo_push_group (cr);
    rsvg_handle_render_cairo (flame_handle, cr);
    cairo_pattern_t *p = cairo_pop_group (cr);

    // Use the temporary surface as a mask for drawing this color
    cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, 0.0);
    cairo_mask(cr, p);
    cairo_restore (cr);

    // Clean up
    cairo_surface_write_to_png (surface, "output.png");
    cairo_pattern_destroy (p);
    cairo_destroy (cr);
    cairo_surface_destroy (surface);
    return 0;
}

Problem when using RSVG and Cairo in Python


By : Kasonge Mabunoa
Date : March 29 2020, 07:55 AM
will be helpful for those in need This is pretty low spread on the internet and I'm posting this to help anyone else with the same question. After tons of searching I found this: https://github.com/jmcb/python-rsvg-dependencies/tree/master/bin. Simply copy all the .dll files into the same folder as the script and it should work.

SVG interaction in python with cairo, opengl and rsvg


By : groxxda
Date : March 29 2020, 07:55 AM
this will help I don't know much about librsvg, but it does not appear to have been updated since 2005, and so I would be inclined to recommend using a different implementation.
If you don't have dependencies on any Python libraries outside of the standard library, then you could use Jython together with Batik. This allows you to add event handlers, as well as change the DOM after rendering.
Related Posts Related Posts :
  • Python hex string encoding
  • Get week start date from week number
  • How to use imports from requirements.txt in python
  • Removing tab indent in ipython shell
  • I need to remove duplicates from a list but add the numeric value in them
  • Delay default arguments being read until function is called
  • Interpolate / fillna with a decay formula in pandas
  • What python package can translate Greek letter to ASCII requivalent?
  • How to get output of OS command from Jupyter notebook?
  • Printing AND writing the RIGHTLY formatted number
  • How do I create a shortcut to import most used python modules?
  • Matplotlib: Show selected date labels on x axis
  • Understanding memoization in Python
  • why does the len function return 2 on some iterations when they are all the same length?
  • Change in preference value does not affect the results of Affinity propagation Clustering
  • returning values inside a function
  • Why cant I use a variable in str slicing?
  • Section divider in Spyder
  • Conditional statement in selenium if element does not exists
  • Pandas : how to select index/row label in dataframe that matches a condition
  • What does zero do in A[0] in this code? Why not empty or another number?
  • Google App Engine urlfetch PayloadTooLargeError: Request exceeds 10 MiB limit for URL
  • Is there a way to set up optional arguments to bypass input arguments?
  • Suppress OpenMP debug messages when running Tensorflow on CPU
  • How to do GridSearchCV for F1-score in classification problem with scikit-learn?
  • Why does .pop() eventually stop and not keep removing items from a list until the list is empty?
  • How do I acess my Spider data from my main.py script?
  • Python Pandas Expand a Column of List of Lists to Two New Column
  • Overhead of python multiprocessing initialization is worse than benefits
  • Python Joining List and adding and removing characters
  • Adding an lxml library to project
  • Concatenating tensors in Tensorflow with None axis
  • Need help understanding why i get attribute error
  • How to force a MIDI device to report control status?
  • What does *** mean in Python -3?
  • How to get GFCC instead of MFCC in python?
  • How do I print a number n times in python?
  • How do i split a string wherever there are digits?
  • List Comprehension Python Prime numbers
  • "list index out of range" when reading data from file
  • What's the correct datetime format for the specified date string?
  • I cannot import CSV file?
  • Matplotlib pyplot plots look different after calling pandas profiling. How can I fix this?
  • Stopping all the instances of a specific region
  • Deal with Birtish summer time
  • Unable to use ColorWheel without loading kv (AttributeError)
  • What are these characters called: 。. !?etc Trying to split sentences stops working with non standard characters
  • rand.randint returning same number over and over?
  • Find longest sequence that does not contain a certain number
  • How do I convert a map object to list and also assign to a variable
  • sympy error: 'Symbol' object has no attribute 'pi'
  • How to remove words without vowels from a list in python
  • Downloading python to macbook
  • TypeError: __init__() missing 1 required positional argument: 'units'
  • Check if a class is a dataclass in Python
  • Unable to scrape google news heading via their class
  • Array of structs with dynamic allocation runs very slow in C in comparison to Python
  • Python Pandas - find all unique combinations of rows of a DataFrame without repeating values in the columns
  • How do I change the numbers in a cell to the word 'Bus' in Pandas Python
  • 'ascii' codec can't encode character : ordinal not in range (128)
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk