Cannot serialize <class 'PIL.Image.Image'> object

Thanks @p.colbert !

I tried

  1. Converting the image to a binary file
  2. Then converting the binary file to a Media Object

and it works now.

In case anyone faces a similar issue, here is the code that worked for me:

import io

def img_to_media_obj(img):
  img_byte_arr = io.BytesIO()
  img.save(img_byte_arr, format='JPEG')
  img_byte_arr = img_byte_arr.getvalue()
  media_obj = anvil.BlobMedia(content_type="image/jpeg", content=img_byte_arr)
  return media_obj

Then in Anvil, putting the returned Media Object into the image’s source attribute.

self.img.source = returned_media_object
3 Likes