I'm trying to crop and resize images in Python, and I want them to be in a fixed format afterwards (47x62 Pixels). However, if the original image is in landscape, my algorithm doesn't work, there are blank areas.
import Image, sys
MAXSIZEX = 47
MAXSIZEY = 62
im = Image.open(sys.argv[1])
(width, height) = im.size
ratio = 1. * MAXSIZEX / MAXSIZEY
im = im.crop((0, 0, int(width*ratio), int(height*ratio)))
im = im.resize((MAXSIZEX, MAXSIZEY), Image.ANTIALIAS)
im.save(sys.argv[2])
I want the resized image to be fully 47x62 - there should be no empty area visible.
You should first check if MAXSIZEX
is greater then the width or the MAXSIZEY
is greater than the height. If they are first rescale the image and then do the cropping:
MAXSIZEX = 64
MAXSIZEY = 42
width, height = im.size
xrat = width / float(MAXSIZEX)
yrat = height / float(MAXSIZEY)
if xrat < 1 or yrat < 1:
rat = min(xrat, yrat)
im = im.resize((int(width / rat), int(height / rat)))
res = im.crop((0, 0, MAXSIZEX, MAXSIZEY))
res.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With