Here is a function, which can be called somewhere to resize images. It works resizing the image to user defined width and height, or setting width (or height) to -1, resize the new dimensions maintaining the same aspect ratio.
It is possible to set even the quality of the image.
def Resize(file,width,height,quality=80):
path,ext=os.path.splitext(file)
name=os.path.basename(path)
try:
image=Image.open(file)
except:
print "Error! -> file:",name+ext
return
w,h=image.size
if width==-1 and height!=-1:
w=height*w/h
h=height
if height==-1 and width!=-1:
h=width*h/w
w=width
if width!=-1 and height!=-1:
w=width
h=height
fmt=image.format
try:
image=image.resize((w,h),Image.ANTIALIAS).save(file,fmt,quality=quality)
except:
print "Error! -> file:",name+ext
return
print name+ext,"...Ok!"
A more complex code is here , it’s a script that use wx as a graphical user interface.
0 comments:
Post a Comment