python - 在 python 中重命名、调整大小和移动图像文件

标签 python ubuntu directory resize renaming

我正在尝试创建一个程序,它将目录中的任何图像调整为 299x299。然后,我想重命名该图像并将其转换为 jpeg,以便将所有图像命名为 0.jpg、1.jpg、2.jpg 等。我还想将转换后的文件移动到自己的目录.

我已经解决了它的调整大小部分。但是,当我添加重命名代码时,即 (index = 0, new_image.save)file_name, str(index), + ".jpg"和 index += 1),调整大小部分不再起作用。有没有人有什么建议?

这是我到目前为止所拥有的:

#!usr/bin/python

from PIL import Image
import os, sys

directory = sys.argv[1]
for file_name in os.listdir(directory):
        print ("Converting %s" % file_name + "...")
        image = Image.open(os.path.join(directory, file_name))

        size = 299, 299
        image.thumbnail(size, Image.ANTIALIAS)

        w, h = image.size

        new_image = Image.new('RGBA', size, (255, 255, 255, 255))
        new_image.paste(image, ((299 - w) / 2, (299 - h) / 2))

        index = 0

        new_image_file_name = os.path.join(directory, file_name)
        new_image.save(file_name, str(index) + ".jpg")

        index += 1

print ("Conversion process complete.")

最佳答案

来自 documentation :

Image.save(fp, format=None, **params)

Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.


image.save 的正确语法是:
new_image.save(file_name, 'JPG')

要移动文件,您可以使用 shutil.move :
import shutil
shutil.move(file_name, 'full/path/to/dst/') # the second argument can be a directory

关于python - 在 python 中重命名、调整大小和移动图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286315/

相关文章:

python - 将应用名称导入项目 urls.py Django

python - 新的主管 - 如何制作一个有效的守护进程

python-3.x - 使用 pip3 安装加密时遇到问题(Ubuntu 16.04 LTS)

Jupyter 中的 R 内核使用了错误的目录

python - 匹配末尾正好 5 位数字的所有名称

linux - 守护进程 : fatal: failed to tell if . ... 是安全的

ruby - 在 Nagiosgraph 中绘制多个磁盘卷

C#/VB.Net - 枚举路径

Java从zip文件中获取顶级文件夹

python - 如何找到两条线段的交点?