image.py 530 B

123456789101112131415161718192021222324
  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