Advertisement
Guest User

PIL transparent image

a guest
Jan 7th, 2012
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import Image
  4.  
  5. IN_DIR = "C:/Users/Karolis/Dropbox/rom/static/images/players"  # Absolute path of directory with images.
  6. OUT_DIR = "transparent_images"              # Name of directory with output contents.
  7. PIXELS_TO_CONVERT = (255, 255, 255)         # Pixels to be rewritten to transparent colour.
  8.  
  9. os.chdir(IN_DIR)                    # Moving to input directory.
  10. try:
  11.     os.mkdir(OUT_DIR)               # Creating output directory.
  12. except WindowsError:
  13.     pass
  14. for f in os.listdir(os.getcwd()):
  15.     if not ".." in f:
  16.         img = Image.open(f)             # Opening image.
  17.         img = img.convert("RGBA")       # Converting to RGBA format.
  18.  
  19.         pixels = img.load()             # Pixel map.
  20.  
  21.         # Looping through pixels and making them transparent where relevant.
  22.         for y in xrange(img.size[1]):
  23.             for x in xrange(img.size[0]):
  24.                 if pixels[x, y] == PIXELS_TO_CONVERT:
  25.                     pixels[x, y] = (255, 255, 255, 0)
  26.  
  27.         os.chdir(OUT_DIR)       # Moving to output directory.
  28.         img.save(f, "PNG")      # Saving transparent image.
  29.         os.chdir(IN_DIR)        # Returning back to input directory.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement