image.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import base64
  2. import io
  3. import numpy as np
  4. import PIL.Image
  5. def img_b64_to_arr(img_b64):
  6. f = io.BytesIO()
  7. f.write(base64.b64decode(img_b64))
  8. img_arr = np.array(PIL.Image.open(f))
  9. return img_arr
  10. def img_arr_to_b64(img_arr):
  11. img_pil = PIL.Image.fromarray(img_arr)
  12. f = io.BytesIO()
  13. img_pil.save(f, format='PNG')
  14. img_bin = f.getvalue()
  15. if hasattr(base64, 'encodebytes'):
  16. img_b64 = base64.encodebytes(img_bin)
  17. else:
  18. img_b64 = base64.encodestring(img_bin)
  19. return img_b64
  20. def img_data_to_png_data(img_data):
  21. with io.BytesIO() as f:
  22. f.write(img_data)
  23. img = PIL.Image.open(f)
  24. with io.BytesIO() as f:
  25. img.save(f, 'PNG')
  26. f.seek(0)
  27. return f.read()
  28. def apply_exif_orientation(image):
  29. try:
  30. exif = image._getexif()
  31. except AttributeError:
  32. exif = None
  33. if exif is None:
  34. return image
  35. exif = {
  36. PIL.ExifTags.TAGS[k]: v
  37. for k, v in exif.items()
  38. if k in PIL.ExifTags.TAGS
  39. }
  40. orientation = exif.get('Orientation', None)
  41. if orientation == 1:
  42. # do nothing
  43. return image
  44. elif orientation == 2:
  45. # left-to-right mirror
  46. return PIL.ImageOps.mirror(image)
  47. elif orientation == 3:
  48. # rotate 180
  49. return image.transpose(PIL.Image.ROTATE_180)
  50. elif orientation == 4:
  51. # top-to-bottom mirror
  52. return PIL.ImageOps.flip(image)
  53. elif orientation == 5:
  54. # top-to-left mirror
  55. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_270))
  56. elif orientation == 6:
  57. # rotate 270
  58. return image.transpose(PIL.Image.ROTATE_270)
  59. elif orientation == 7:
  60. # top-to-right mirror
  61. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_90))
  62. elif orientation == 8:
  63. # rotate 90
  64. return image.transpose(PIL.Image.ROTATE_90)
  65. else:
  66. return image