简体   繁体   中英

Python Image (PIL) library not resizing properly per kwargs

Here is my code:

import Image
import sys
import json

if __name__ == '__main__':
    args = json.loads(sys.argv[1])
    srcPath = args.get('srcPath')
    image = Image.open(srcPath)
    sizes = {}

    for variant_name, dimensions in args.get('sizes').items():
        if '%' in dimensions:
            sizes[variant_name] = image.size
        else:
            width = int(dimensions.split('x')[0])
            height = int(dimensions.split('x')[1])
            widthAndHeight = (width, height)
            sizes[variant_name] = widthAndHeight

    for key, val in sizes.items():
        imageName = key + '.' + srcPath.split('.')[1]
        convertedImage = image.resize(val, Image.ANTIALIAS)
        image.save(imageName)
        print 'done'

And I'm calling it with:

python image.py '{"sizes":{"large":"200x150","orig":"100%x100%"},"srcPath":"/Users/bobcobb/Desktop/avocado.png"}'

If the argument 100%x100% is passed in, then I want to resize to the original size, otherwise, I want to resize to the passed in size. So the above code would generate 2 images (one original, the other 200x150).

Right now, it just saves the image as the original size for both. How can I fix this?

Your problem is that the resized image is assigned to convertedImage , but you save the original image (at the new filename).

So changing this line

image.save(imageName)

into

convertedImage.save(imageName)

solves this problem.

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