使用Reportlab使旋转的图像居中

西里尔·N。

我试图将旋转后的图像放在Reportlab上居中,但是在使用正确的展示位置计算时遇到了问题。

这是当前代码:

from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from PIL import Image as PILImage

import requests
import math


def main(rotation):
    # create a new PDF with Reportlab
    a4 = (595.275590551181, 841.8897637795275)
    c = canvas.Canvas('output.pdf', pagesize=a4)
    c.saveState()

    # loading the image:
    img = requests.get('https://i.stack.imgur.com/dI5Rj.png', stream=True)

    img = PILImage.open(img.raw)
    width, height = img.size

    # We calculate the bouding box of a rotated rectangle
    angle_radians = rotation * (math.pi / 180)
    bounding_height = abs(width * math.sin(angle_radians)) + abs(height * math.cos(angle_radians))
    bounding_width = abs(width * math.cos(angle_radians)) + abs(height * math.sin(angle_radians))

    a4_pixels = [x * (100 / 75) for x in a4]

    offset_x = (a4_pixels[0] / 2) - (bounding_width / 2)
    offset_y = (a4_pixels[1] / 2) - (bounding_height / 2)
    c.translate(offset_x, offset_y)

    c.rotate(rotation)
    c.drawImage(ImageReader(img), 0, 0, width, height, 'auto')

    c.restoreState()
    c.save()


if __name__ == '__main__':
    main(45)

到目前为止,这是我所做的:

  1. 计算旋转矩形的边界(因为矩形会更大)
  2. 使用这些来计算宽度和高度的图像中心位置(大小/ 2-图像/ 2)。

出现两个我无法解释的问题:

  1. “ a4”变量以磅为单位,其他所有像素。如果我将其更改为用于计算位置的像素(使用,这是合乎逻辑的a4_pixels = [x * (100 / 75) for x in a4])。旋转0度时放置不正确。如果我保持a4的分数,它可以工作...?
  2. 如果我改变旋转角度,它会断裂得更多。

因此,我的最后一个问题是:如何计算offset_xoffset_y值,以确保无论旋转如何始终将其居中?

谢谢!:)

平移画布时,实际上是在移动原点(0,0),并且所有绘制操作都将相对于原点。

因此,在下面的代码中,我将原点移动到了页面的中间。然后,我旋转“页面”并将图像绘制在“页面”上。由于其画布轴已旋转,因此无需旋转图像。

from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from reportlab.lib.pagesizes import A4
from PIL import Image as PILImage
import requests

def main(rotation):
    c = canvas.Canvas('output.pdf', pagesize=A4)
    c.saveState()

    # loading the image:
    img = requests.get('https://i.stack.imgur.com/dI5Rj.png', stream=True)
    img = PILImage.open(img.raw)
    # The image dimensions in cm
    width, height = img.size

    # now move the canvas origin to the middle of the page
    c.translate(A4[0] / 2, A4[1] / 2)
    # and rotate it
    c.rotate(rotation)
    # now draw the image relative to the origin
    c.drawImage(ImageReader(img), -width/2, -height/2, width, height, 'auto')

    c.restoreState()
    c.save()

if __name__ == '__main__':
    main(45)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章