我有一些我想下载的 PNG 图像链接,“转换为缩略图”并使用 Python 和 Cairo 保存为 PDF。
现在,我有一个工作代码,但我不知道如何控制纸上的图像大小。有没有办法将 PyCairo Surface 的大小调整为我想要的尺寸(恰好比原来的小)?我希望将原始像素“缩小”到更高分辨率(在纸上)。
另外,我尝试Image.rescale()
了 PIL 的函数,但它给了我一个 20x20 像素的输出(在 200x200 像素的原始图像中,这不是代码上的横幅示例)。我想要的是一个 200x200 像素的图像,绘制在纸上 20x20 平方毫米的正方形内(而不是我现在得到的 200x200 平方毫米)
我目前的代码是:
#!/usr/bin/python
import cairo, urllib, StringIO, Image # could I do it without Image module?
paper_width = 210
paper_height = 297
margin = 20
point_to_milimeter = 72/25.4
pdfname = "out.pdf"
pdf = cairo.PDFSurface(pdfname , paper_width*point_to_milimeter, paper_height*point_to_milimeter)
cr = cairo.Context(pdf)
cr.scale(point_to_milimeter, point_to_milimeter)
f=urllib.urlopen("http://cairographics.org/cairo-banner.png")
i=StringIO.StringIO(f.read())
im=Image.open(i)
# are these StringIO operations really necessary?
imagebuffer = StringIO.StringIO()
im.save(imagebuffer, format="PNG")
imagebuffer.seek(0)
imagesurface = cairo.ImageSurface.create_from_png(imagebuffer)
### EDIT: best answer from Jeremy, and an alternate answer from mine:
best_answer = True # put false to use my own alternate answer
if best_answer:
cr.save()
cr.scale(0.5, 0.5)
cr.set_source_surface(imagesurface, margin, margin)
cr.paint()
cr.restore()
else:
cr.set_source_surface(imagesurface, margin, margin)
pattern = cr.get_source()
scalematrix = cairo.Matrix() # this can also be used to shear, rotate, etc.
scalematrix.scale(2,2) # matrix numbers seem to be the opposite - the greater the number, the smaller the source
scalematrix.translate(-margin,-margin) # this is necessary, don't ask me why - negative values!!
pattern.set_matrix(scalematrix)
cr.paint()
pdf.show_page()
请注意,漂亮的开罗横幅甚至不适合页面...理想的结果是我可以以用户空间单位(在本例中为毫米)控制此图像的宽度和高度,以创建漂亮的标题图像,例如。
感谢您的阅读和任何帮助或评论!!