No Description

thumbnail_utils.py 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -*- coding: utf-8 -*-
  2. from __future__ import division
  3. try:
  4. from cStringIO import StringIO
  5. from cStringIO import StringIO as BytesIO
  6. except ImportError:
  7. try:
  8. from StringIO import StringIO
  9. from StringIO import StringIO as BytesIO
  10. except ImportError:
  11. from io import BytesIO, StringIO
  12. try:
  13. from PIL import Image
  14. except ImportError:
  15. import Image
  16. def make_thumbnail(im_path, im_thumbnail_path=None, max_width=360):
  17. im = Image.open(im_path)
  18. width, height = im.size
  19. thumb_width = min(max_width, width)
  20. thumb_height = height / width * thumb_width
  21. im.thumbnail((thumb_width, thumb_height), Image.ANTIALIAS)
  22. im.save(im_thumbnail_path or im_path, im.format or 'JPEG', quality=90)
  23. return width, height, thumb_width, thumb_height
  24. def make_thumbnail2(data, w=360, h=240):
  25. im = Image.open(BytesIO(data))
  26. fmt = im.format.lower()
  27. width, height = im.size
  28. if width <= w and height <= h:
  29. return data
  30. if width > height:
  31. thumb_width, thumb_height = w, height * w / width
  32. else:
  33. thumb_width, thumb_height = width * h / height, h
  34. im.thumbnail((thumb_width, thumb_height), Image.ANTIALIAS)
  35. out = BytesIO()
  36. im.save(out, format=fmt)
  37. data = out.getvalue()
  38. return data