Rotating an image with pyCairo
Asked Answered
S

1

6

I'm having trouble understanding how to simply rotate an image with pyCairo...

Here's what I did, based on this example :

image_surface = cairo.ImageSurface.create_from_png(image_path)
width = image_surface.get_width()
height = image_surface.get_height()

context = cairo.Context(cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height))

context.translate(width*0.5, height*0.5)
context.rotate(45.0*math.pi/180.0)
context.scale(1.0, 1.0)
context.translate(-width*0.5, -height*0.5)

context.set_source_surface(image_surface, 0, 0)
context.paint()

image_surface.write_to_png(output_path)

The output image is identical to the initial image. What am I missing ?

Screech answered 4/1, 2016 at 16:34 Comment(0)
T
6

There are 2 problems:

  1. You must use the cairo.ImageSurface instance to write the new image:

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    context = cairo.Context(surface)
    (...)
    surface.write_to_png(output_path)
    
  2. You must switch the instructions context.scale and context.translate:

    context.translate(width*0.5, -height*0.5)
    context.scale(1.0, 1.0)
    

By the way, the width and height of the the new image should be recalculated.

Tater answered 4/1, 2016 at 17:2 Comment(1)
Thank you. It's now working. I was mostly confused with the use of Surface, and I didn't get that the Surface I had to write_to_png was the one created for the context, and not the one set as source_surface of the context later.Screech

© 2022 - 2024 — McMap. All rights reserved.