【问题标题】:Can't paste resized image in Pillow无法在 Pillow 中粘贴调整大小的图像
【发布时间】:2019-12-22 23:23:29
【问题描述】:

我在 Pillow 模块中粘贴调整大小的图像时遇到问题。我想将水印调整到所有图像宽度为图像宽度的 1/3 的所有图像,并保持 65:10 的比例,粘贴调整大小的图像后出现此错误:

(480, 360)
(160, 25)
Traceback (most recent call last):
  File "C:/Users/Przemek/PycharmProjects/cwiczenia/venv/project watermark.py", line 15, in <module>
    image.paste(watermarkResized, (0,0))
  File "C:\Users\Przemek\PycharmProjects\cwiczenia\venv\lib\site-packages\PIL\Image.py", line 1504, in paste
    raise ValueError("cannot determine region size; use 4-item box")
ValueError: cannot determine region size; use 4-item box

代码如下:

import os
from PIL import Image
directory = "PATH TO THE DIRECTORY"
watermark = Image.open("PATH TO THE WATERMARK")

for filename in os.listdir(directory):
    image = Image.open("PATH TO THE DIRECTORY"+filename)
    imageWidth, imageHeight = (image.size)
    watermarkResized = watermark.resize(((int(round((imageWidth/3),0)), int(round(((imageWidth/3) /6.5),0))))).copy

    print(image.size)
    print(watermarkResized.size)


    image.paste(watermarkResized, (0,0))
    image.save("PATH TO THE DIRECTORY"+filename+".png")

【问题讨论】:

  • 使用//而不是/你会得到整数结果 - imageWidth//3 - 你将不需要round()int()
  • paste 需要四个值(0, 0, width, height) 或更详细的(x1, y1, x2, y2)
  • 谢谢,我一开始是这样做的,后来我用round()函数做了实验。

标签: python python-imaging-library


【解决方案1】:

paste 需要四个值(x1, y1, x2, y2)

在你的代码中可能是

width, height = watermarkResized.size

image.paste(watermarkResized, (0, 0, width, height))

【讨论】:

    【解决方案2】:

    我通过简单地从图像对象中删除 .copy 函数解决了这个问题。我现在有另一个问题。如何将具有透明背景的 .png 图像粘贴到图像中?

    【讨论】:

    • 好的,这个我也修好了,谢谢帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-01-08
    • 2022-01-23
    • 2016-06-09
    • 2015-06-04
    • 2014-07-18
    • 1970-01-01
    • 2016-03-23
    • 2020-05-05
    相关资源
    最近更新 更多