Guest User

full-color GIF simple

a guest
Feb 19th, 2013
393
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python2
  2.  
  3. import sys
  4. import os.path
  5. from PIL import Image
  6. from collections import Counter
  7.  
  8. # Get the input file path:
  9. _,path = sys.argv
  10. root, _ = os.path.splitext(path)
  11.  
  12. # Open input image:
  13. img = Image.open(path)
  14. dat = img.getdata()
  15. w,h = img.size
  16. col = [ rgb for (rgb, cnt) in Counter(dat).most_common() ]
  17. rev = dict((rgb,i) for (i, rgb) in enumerate(col))
  18. idx = [ rev[rgb] for rgb in dat ]
  19.  
  20. # Generate a list of output images:
  21. out = Image.new('P', img.size)
  22. nfr = (len(col) + 253)//255
  23. opt = {}
  24. for frame in range(nfr):
  25.     start = 255*frame + 1
  26.     end   = min(start + 255, len(col))
  27.     out.putpalette(sum(col[start - 1:end], tuple()))
  28.     out.putdata([ 1 + i - start if start <= i < end else 0 for i in idx ])
  29.     out.save('%s-%04d.gif' % (root, frame), **opt)
  30.     opt['transparency'] = 0  # all frames except the first use transparency
  31.  
  32. # Since PIL doesn't support creating multi-frame GIF files, the resulting
  33. # files must be converted with another tool.  I used gifsicle.
RAW Paste Data