python - 使用 PIL 在 python 中调整图像大小

标签 python python-imaging-library

我正在尝试调整一组图像的大小,大约为 366,因此我创建了一个脚本,我首先在 3 上进行了测试,结果成功了。

问题是当我处理整个文件夹时,它返回这个错误:

resizeimage.imageexceptions.ImageSizeError: 'Image is too small, Image size : (275, 183), Required size : (399, 399)'

我的脚本应该迭代整个文件夹,调整图像大小,然后将输出文件存储在另一个文件夹中:

import os

from PIL import Image

from resizeimage import resizeimage

path = "/Users/sigc2sige/PycharmProjects/helloworld/photos"
size = (399, 399)

for file in os.listdir(path):
    with open('/Users/sigc2sige/PycharmProjects/helloworld/photos/'+file, 'r+b') as f:
        with Image.open(f) as image:
            cover = resizeimage.resize_cover(image, size, Image.ANTIALIAS)
            cover.save('/Users/sigc2sige/PycharmProjects/helloworld/photos_2/'+file, image.format)

我确实使用了这条指令:

thumb = ImageOps.fit(image, size, Image.ANTIALIAS) 但我相信它会裁剪图像而不是调整图像大小。

如果您对如何解决这个问题有任何想法,那就太好了。

最佳答案

对图像进行下采样(使其变小)是一回事,而对图像进行上采样(使其变大)则是另一回事。如果你想降采样,ANTIALIAS 是一个不错的选择,如果你想升采样,你可以使用其他过滤器。

import os

from PIL import Image

from resizeimage import resizeimage

path = "/Users/sigc2sige/PycharmProjects/helloworld/photos"
size = (399, 399)

for file in os.listdir(path):
    with open('/Users/sigc2sige/PycharmProjects/helloworld/photos/'+file, 'r+b') as f:
        with Image.open(f) as image:
            if (image.size) >= size:
                cover = resizeimage.resize_cover(image, size, Image.ANTIALIAS)
                cover.save('/Users/sigc2sige/PycharmProjects/helloworld/photos_2/'+file, image.format)
            else:
                cover = image.resize(size, Image.BICUBIC).save('/Users/sigc2sige/PycharmProjects/helloworld/photos_2/'+file, image.format)

关于python - 使用 PIL 在 python 中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57361872/

相关文章:

python - 如何将此代码转换为 for 循环格式?

python - 有没有一种精确的方法来测量Python(3.7)中特定字体的文本大小?

python - 旋转后的图片看起来像缺少像素

Python 列表和运算符

python - 在python中读取以utf-8编码的阿拉伯文本

python - 无法筛选 aws lambda 函数的 boto3 日志流

python - TF Keras v 1.14+ : subclass model or subclass layer for "module"

保存图像时 Python Pillow 编码器错误 -2

python - 如何将不是黑色的每个像素转换为某种颜色?

python - 无法在 PIL 中的 16 位 TIF 上应用图像滤镜