Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Tue May 14 23:46:56 2019
- @author: Xander
- """
- from PIL import Image
- import os
- import tkinter as tk
- from tkinter import filedialog
- def matteImg(imgPath):
- im = Image.open(imgPath)
- # create a white 1:1 square background in the right size and merge it
- whtIm = Image.new(im.mode,(max(im.size),max(im.size)),color=(255,255,255))
- if im.size[0]/im.size[1]>1:
- # landscape
- whtIm.paste(im,(0,(whtIm.size[1]-im.size[1])//2))
- elif im.size[0]/im.size[1]<1:
- # portrait
- whtIm.paste(im,((whtIm.size[0]-im.size[0])//2,0))
- else:
- # already 1:1
- whtIm = im
- # save the file
- inFileName = os.path.split(imgPath)[1]
- outFileName = inFileName.split('.')[0] + '_matted.' + inFileName.split('.')[1]
- outfile = os.path.join(os.path.split(imgPath)[0],outFileName)
- whtIm.save(outfile,'JPEG')
- im.close
- def scanForImages(dirPath, searchSubDirectory=False):
- for file in os.listdir(dirPath):
- filename = os.fsdecode(file)
- if os.path.isfile(os.path.join(dirPath,file)):
- if filename.endswith('.jpg'):
- print('Found an image: ' + filename)
- imgPath = os.path.join(dirPath,filename)
- matteImg(imgPath)
- elif os.path.isdir(os.path.join(dirPath,file)):
- print('Found a folder: ' + dirPath+ '/' + file)
- if searchSubDirectory:
- scanForImages(dirPath + '/' + file)
- else:
- print('Found neither :/')
- root = tk.Tk()
- root.withdraw()
- folder_path = filedialog.askdirectory()
- scanForImages(folder_path)
Advertisement
Add Comment
Please, Sign In to add comment