Guest User

web app python by simdia

a guest
Nov 4th, 2016
81
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # FixImage.py 2016
  2. from PIL import Image # Pillow (http://python-pillow.github.io/) is a great python3-supporting PIL fork
  3.  
  4. def FixImage(img, max_width=None, max_height=None):
  5. '''
  6. Strips an image of everything but its basic data (nasty EXIF tags, gif animations, etc.), first correcting orientation if necessary.
  7.  
  8. 'img' must be a PIL.Image.Image instance. Returns a new instance. Requires the PIL.Image (Python Image Library) or equivalent to be imported as Image; image formats supported depend on PIL prereqs installed on the system (see http://pillow.readthedocs.io/en/3.0.x/installation.html).
  9.  
  10. If max_width and/or max_height are supplied (pixels as int), the image is proportionally downsized to fit the tighter of the two constraints using a high-quality downsampling filter.
  11. '''
  12.  
  13. ORIENT = { # exif_val: (rotate degrees cw, mirror 0=no 1=horiz 2=vert); see http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
  14. 2: (0, 1),
  15. 3: (180, 0),
  16. 4: (0, 2),
  17. 5: (90, 1),
  18. 6: (270, 0),
  19. 7: (270, 1),
  20. 8: (90, 0),
  21. }
  22.  
  23. assert isinstance(img, Image.Image), "Invalid 'img' parameter to fix_image()"
  24. img_format = img.format
  25.  
  26. # fix img orientation (issue with jpegs taken by cams; phones in particular):
  27. try:
  28. orient = img._getexif()[274]
  29. except (AttributeError, KeyError, TypeError, ValueError):
  30. orient = 1 # default (normal)
  31. if orient in ORIENT:
  32. (rotate, mirror) = ORIENT[orient]
  33. if rotate:
  34. img = img.rotate(rotate)
  35. if mirror == 1:
  36. img = img.transpose(Image.FLIP_LEFT_RIGHT)
  37. elif mirror == 2:
  38. img = img.transpose(Image.FLIP_TOP_BOTTOM)
  39.  
  40. # strip image
  41. data = img.getdata()
  42. palette = img.getpalette()
  43. img = Image.new(img.mode, img.size)
  44. img.putdata(data)
  45. if palette:
  46. img.putpalette(palette)
  47.  
  48. # resize image (if necessary):
  49. (width, height) = img.size
  50. if max_width and width > max_width and (not max_height or width*max_height >= height*max_width): # width is constraint
  51. img = img.resize((max_width, round(height*max_width/width)), Image.LANCZOS)
  52. elif max_height and height > max_height: # height is constraint
  53. img = img.resize((round(width*max_height/height), max_height), Image.LANCZOS)
  54.  
  55. img.format = img_format # preserve orig format
  56. return img
  57.  
  58. if __name__ == "__main__": # run this script as-is for a basic test
  59. # *****************
  60. # * Usage Example *
  61. # *****************
  62. infile = input('Input image filename: ')
  63. try:
  64. img = Image.open(infile)
  65. except IOError as err:
  66. print('Error opening file:', str(err))
  67. img = None
  68. if img:
  69. if img.format:
  70. print('Image format:', img.format) # use in Content-Type: image/format header when returning image over the web)
  71. outfile = input('Output image filename: ')
  72. max_width = int(input('New max width (0 for none): '))
  73. max_height = int(input('New max height (0 for none): '))
  74.  
  75. FixImage(img, max_width, max_height).save(outfile, img.format)
  76. # alternatively, to get the image binary instead of writing it back to a file (python3):
  77. # > from io import BytesIO
  78. # > new_img = BytesIO()
  79. # > FixImage(img, max_width, max_height).save(new_img, img.format)
  80. # > new_image_binary = new_img.getvalue()
  81. print('New image saved.')
  82. else:
  83. print('Unrecognized image format.')
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×