简体   繁体   中英

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

Here is my code :

# -*- 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()

If I let this script to save resized images in the folder named "path", it resizes all images and saves there but it creates a mess, I mean unresized and resized images all in one directory. When I try to write a solution like that, it only saves one picture in the directory that i show in the last line. Can you help me in this?

Try

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

or, equivalently

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

and, from Python 3.6 onwards, it's easier to write

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

At present you are trying to create a single output file called *.jpg for each input file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM