gpt4 book ai didi

python - pyCairo:如何调整图像的大小和位置?

转载 作者:太空狗 更新时间:2023-10-29 21:09:05 25 4
gpt4 key购买 nike

基于问题Create PDF with (resized) PNG images using Pycairo - rescaling Surface issue我试图创建重新缩放图像并将图像放置在特定位置的代码,如下面的代码所示(例如,在这种情况下,图像应该出现在下面的矩形“上方”)。但是,我似乎无法让图像出现在正确的位置。

如果知道必须更改哪些内容才能正确缩放图像,我将不胜感激。

import cairo
if not cairo.HAS_PDF_SURFACE:
raise SystemExit('cairo was not compiled with PDF support')


def draw_image(ctx, image, top, left, height, width):
"""Draw a scaled image on a given context."""
image_surface = cairo.ImageSurface.create_from_png(image)
# calculate proportional scaling
img_height = image_surface.get_height()
img_width = image_surface.get_width()
width_ratio = float(width) / float(img_width)
height_ratio = float(height) / float(img_height)
scale_xy = min(height_ratio, width_ratio)
# scale image and add it
ctx.save()
ctx.scale(scale_xy, scale_xy)
ctx.translate(left, top)
ctx.set_source_surface(image_surface)

ctx.paint()
ctx.restore()


def draw_box(ctx, left, top, width, height):
"""Draw a box on a given context."""
ctx.rectangle(left, top, width, height)
ctx.set_source_rgb(1, 1, 1)
ctx.fill()
ctx.rectangle(left, top, width, height)
ctx.set_source_rgb(0, 0, 0)
ctx.stroke()


# A4 Page (in points)
surface = cairo.PDFSurface("box.pdf", 595, 842)
context = cairo.Context(surface)
# sizes (in points)
height = 250
width = 180
margin = 20
# draw boxes
draw_box(context, margin, margin, width, height)
draw_box(context, margin + width, margin + height, width, height)
# draw images - SHOULD be superimposed over rectangles, but are NOT
image = "hello.png"
draw_image(context, image, margin, margin, height, width)
draw_image(context, image, margin + height, margin + width, height, width)

最佳答案

切换比例和平移的顺序。先翻译,再缩放。

关于python - pyCairo:如何调整图像的大小和位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7145780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com