Guest User

Untitled

a guest
May 22nd, 2020
342
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys
  2. import os
  3. from PIL import Image
  4. from PIL import ImageChops
  5. from PIL import ImageFile
  6. ImageFile.LOAD_TRUNCATED_IMAGES = True
  7. import math
  8.  
  9. def trim(im):
  10.     bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
  11.     diff = ImageChops.difference(im, bg)
  12.     diff = ImageChops.add(diff, diff, 2.0, -100)
  13.     bbox = diff.getbbox()
  14.     if bbox:
  15.         return im.crop(bbox)
  16.        
  17. dir = os.fsencode('./18')
  18. images = [1 for file in os.listdir(dir)]
  19. n = len(images)
  20. size = 6000
  21. basic_height = 300
  22. background = Image.new('RGBA', (size, size), (0, 0, 0, 255))
  23. x = 1
  24. y = 1
  25. i = 0
  26. for file in os.listdir(dir):
  27.     i += 1
  28.     print(n, i, file)
  29.     image = Image.open(os.path.join(dir, os.fsencode(file)))
  30.     curr_x, curr_y = image.size
  31.     image.thumbnail((math.floor(curr_x / curr_y * basic_height), basic_height), Image.ANTIALIAS)
  32.     if x + image.size[0] > size:
  33.         x = 1
  34.         y += basic_height
  35.     background.paste(image, (x, y))
  36.     x += image.size[0]
  37.     if x > size:
  38.         x = 1
  39.         y += basic_height
  40.     if y > size:
  41.         print('NOT ENOUGH PLACE')
  42. trim(background).save('result_18.png')
RAW Paste Data