8
基於Create PDF with (resized) PNG images using Pycairo - rescaling Surface issue這個問題,我試圖創建代碼來重新縮放並將圖像放置在特定的位置,如下面的代碼所示(在這種情況下,例如,圖像應該出現在底層矩形上方)。但是,我似乎無法讓圖像出現在正確的位置。pyCairo:如何調整圖像大小和位置?
我會很感激知道我必須改變,以便爲和正確定位圖像。
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)
你不可能得到很好的答案,因爲人們不能運行這個代碼來測試它。請儘可能使用自包含的示例進行更新(並鏈接到需要運行的任何模塊/圖像/等) – agf
等待。你*安裝* PyCairo?不可能。 – batman
@agf - 其實這是一個自包含的腳本......當你嘗試運行它時遇到了什麼問題?唯一需要的模塊是cairo。 – Derek