Guest User

whiteout

a guest
Jun 30th, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue May 14 23:46:56 2019
  4.  
  5. @author: Xander
  6. """
  7.  
  8. from PIL import Image
  9. import os
  10. import tkinter as tk
  11. from tkinter import filedialog
  12.  
  13. def matteImg(imgPath):    
  14.     im = Image.open(imgPath)
  15.    
  16.     # create a white 1:1 square background in the right size and merge it
  17.     whtIm = Image.new(im.mode,(max(im.size),max(im.size)),color=(255,255,255))
  18.    
  19.     if im.size[0]/im.size[1]>1:
  20.         # landscape
  21.         whtIm.paste(im,(0,(whtIm.size[1]-im.size[1])//2))
  22.     elif im.size[0]/im.size[1]<1:
  23.         # portrait
  24.         whtIm.paste(im,((whtIm.size[0]-im.size[0])//2,0))
  25.     else:
  26.         # already 1:1
  27.         whtIm = im
  28.        
  29.     # save the file
  30.     inFileName = os.path.split(imgPath)[1]
  31.     outFileName = inFileName.split('.')[0] + '_matted.' + inFileName.split('.')[1]
  32.     outfile = os.path.join(os.path.split(imgPath)[0],outFileName)
  33.     whtIm.save(outfile,'JPEG')
  34.     im.close
  35.    
  36. def scanForImages(dirPath, searchSubDirectory=False):
  37.     for file in os.listdir(dirPath):
  38.         filename = os.fsdecode(file)
  39.         if os.path.isfile(os.path.join(dirPath,file)):
  40.             if filename.endswith('.jpg'):
  41.                 print('Found an image: ' + filename)
  42.                 imgPath = os.path.join(dirPath,filename)
  43.                 matteImg(imgPath)
  44.         elif os.path.isdir(os.path.join(dirPath,file)):
  45.             print('Found a folder: ' + dirPath+ '/' + file)
  46.             if searchSubDirectory:
  47.                 scanForImages(dirPath + '/' + file)
  48.         else:
  49.             print('Found neither :/')
  50.              
  51. root = tk.Tk()
  52. root.withdraw()
  53.  
  54. folder_path = filedialog.askdirectory()
  55.  
  56. scanForImages(folder_path)
Advertisement
Add Comment
Please, Sign In to add comment