使用pyCairo旋转图像

6

我遇到了一些困难,不太明白如何使用pyCairo简单地旋转图像...

这是我根据这个例子做的:

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)

输出的图像与初始图像完全相同。 我错过了什么吗?
1个回答

6

有两个问题:

  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)
    

顺便提一下,新图片的宽度和高度应该重新计算。


谢谢。现在它正在工作。我最初对Surface的使用感到困惑,我没有意识到我需要写入PNG的Surface是为上下文创建的那个,而不是稍后设置为上下文源Surface的那个。 - Kyrill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接