簡體   English   中英

將所有圖像調整大小后如何在Python(PIL)中保存大量圖像?

[英]How can I save lots of images after resizing them all into another directory in Python(PIL)?

這是我的代碼:

# -*- coding: utf-8 -*-
#!/usr/bin/python

import PIL

from PIL import Image

import os,sys

path = "/home/ozer/Desktop/Yedek/Workspace/"

dirs = os.listdir (path)

def resize():

        for item in dirs:
            if os.path.isfile(path1+item):
                 img = Image.open(path1+item)
                 f,e = os.path.splitext(path1+item)
                 basewidth = 100
                 wpercent = (basewidth / float(img.size[0]))
                 hsize = int((float(img.size[1]) * float(wpercent)))
                 img = img.resize((basewidth, hsize))
                 img.save("/home/ozer/Desktop/Scripts/Last/"+"*.jpg","JPEG")

resize()

如果我讓此腳本將經過調整大小的圖像保存在名為“ path”的文件夾中,它將調整所有圖像的大小並保存在此處,但會造成混亂,我的意思是將未調整大小和調整大小的圖像全部保存在一個目錄中。 當我嘗試編寫這樣的解決方案時,它只會在最后一行顯示的目錄中保存一張圖片。 你能幫我嗎?

嘗試

img.save("/home/ozer/Desktop/Scripts/Last/"+item+".jpg","JPEG")

或者,等效地

img.save("/home/ozer/Desktop/Scripts/Last/{}.jpg".format(item),"JPEG")

從Python 3.6開始,編寫起來更加容易

img.save(f"/home/ozer/Desktop/Scripts/Last/{item}.jpg","JPEG")

目前,您正在嘗試為每個輸入文件創建一個名為*.jpg的輸出文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM