image.py 768 B

1234567891011121314151617181920212223242526272829303132333435
  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()