image.py 2.1 KB

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