Created
January 23, 2021 01:01
-
-
Save emjayoh/9543967ddb8b02b44f822f1c8e960f79 to your computer and use it in GitHub Desktop.
[Batch process images] resize/crop #python #graphics #batch #resize #crop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Python 2.7, PIL 1.1.7 | |
| import Image | |
| import glob | |
| import os | |
| #Function to resize image, preserving aspect ratio | |
| def resizeAspect(im, size): | |
| w,h = im.size | |
| aspect=min(size[0]/float(w), size[1]/float(h)) | |
| return im.resize((int(w*aspect),int(h*aspect)),Image.ANTIALIAS) | |
| imgList=glob.glob('C:/icons/*.png') #Find all png images in a directory | |
| for img in imgList: #Loop through all found images | |
| im = Image.open(img) #open the image | |
| print "resizing:",os.path.basename(img) | |
| w,h = im.size #Get image width and height | |
| if min(w,h)<600: #Check if either dimension is smaller then 600 | |
| im=resizeAspect(im,(600,600)) #Re-size Image | |
| w,h = im.size #update image size | |
| center = [int(w/2.0),int(h/2.0)] #Calculate Center | |
| box = (center[0]-300, center[1]-300, center[0]+300, center[1]+300) #Defines a box where you want it to be cropped | |
| croppedIm = im.crop(box) #Crop the image | |
| #croppedIm.show() #Show the cropped image | |
| fileName, fileExtension=os.path.splitext(img) | |
| croppedIm.save(fileName+'_crop.png', "PNG") #Save the cropped image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment