python - 如何使用for循环将图像保存在文件夹中?

标签 python image resize processing rescale

首先,我在将每个具有相同名称的调整大小的文件保存到同一文件夹时遇到问题?其次,在运行时我无法理解 m t 代码是否正常工作。请您检查一下我是否正确调整了大小?在我的代码中找不到错误:

import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR)
      imgResult.save('"C:/Users/marialavrovskaa/Desktop/Images/file_%d.jpg"', 'JPEG')
        print("All good")

最佳答案

如果您想为图像指定一个带有连续数字的名称,则必须连接文件名和计数器:

image_no = 1
for image in images:

    # [...]

    name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
    imgResult.save(name, 'JPEG')
    image_no += 1

由于图像的格式为PNG并且应存储为JPEG,因此格式必须从RGBA转换为< em>RGB,作者:.convert('RGB') 。请注意,将 RGBA 图像存储为“JPGE”会导致错误:

import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
        name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
        imgResult.save(name, 'JPEG')
        image_no += 1
        print("All good")
<小时/>

顺便说一句,如果文件名应该保留并且图像应该存储到具有不同扩展名的文件中,那么可以通过 .splitext 将扩展名从文件中分割出来。 :

import os
imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
name = os.path.splitext(image)[0] + '.jpg'
imgResult.save(name, 'JPEG')
<小时/>

如果您想将文件存储到不同的路径并使用不同的扩展名,那么您必须从该路径中提取文件名称。

参见os.path 。通过 os.path.split(path) 将路径从文件名和扩展名中分割出来,返回路径和名称的元组。

例如

>>> import os
>>> os.path.split('c:/mydir/myfile.ext')
('c:/mydir', 'myfile.ext')

通过os.path.splitext(path)分割文件名和扩展名:

>>> os.path.splitext('myfile.ext')
('myfile', '.ext')

应用于您的代码,这意味着,其中 file 是源图像文件的路径、名称和扩展名:

import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
    with open(image,"rb") as file:
        img = Image.open(file)
        imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')

        image_path_and_name = os.path.split(file) 
        image_name_and_ext = os.path.splitext(image_path_and_name[1]) 
        name = image_name_and_ext[0] + '.png'
        file_path = os.path.join(path, name)

        imgResult.save(file_path , 'JPEG')
        image_no += 1
        print("All good")

关于python - 如何使用for循环将图像保存在文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56311318/

相关文章:

Python Eve Auth 无法返回 401 异常

image - 使用 CSS3 仅显示部分背景图像

Python- raw_input 不工作

python - 创建一个Bruteforce程序,该程序可对随机非重复数字进行混洗。收到ValueError-不确定为什么吗?

Java,我的图像不会更新/移动

c++ - 在 vector 中使用删除或调整大小哪个更快?

c# - Windows 窗体 C# : Resize Label image on runtime when resizing the label

html - 2 完全相同的 HTML 页面根据托管呈现不同

python - 如何获取 N 阶张量的任意列?

ios - React Native 0.26 在显示 Assets 库中的图像时找不到合适的图像 URL 加载器