【问题标题】:How to save images in a folder with for loop?如何使用for循环将图像保存在文件夹中?
【发布时间】:2019-05-26 06:47:49
【问题描述】:

首先,我在将每个调整大小的同名文件保存到同一个文件夹时遇到问题?其次,在运行时我无法理解 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")

【问题讨论】:

    标签: python image resize processing rescale


    【解决方案1】:

    如果你想给图像一个连续数字的名字,而不是连接文件名和一个计数器:

    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转换为RGB em>,.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")
    

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多