image.py 2.0 KB

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