When using Anvil to call a function in Google Colab, I want to return several images (PIL) from the function.
I want to then display the returned image results onto the Anvil UI.
However, I’m getting this error code:
SerializationError: Cannot serialize return value from function. Cannot serialize <class 'PIL.Image.Image'> object at msg['response'][0]
My code:
def submit_button_click(self, **event_args):
# search() function returns a list of three images
results = anvil.server.call('search', self.input.text)
if results:
self.result_img1.visible = True
self.result_img2.visible = True
self.result_img3.visible = True
self.result_img1.source = results[0]
self.result_img2.source = results[1]
self.result_img3.source = results[2]
Welcome to Anvil’s Community Forum!
Let’s start here: Valid arguments and return values. Anvil knows how to convert some kinds of data objects, for transmission over the wire, but it can’t possibly know how to do every data type. This is especially true when the type is defined outside of Anvil.
Fortunately, an image is effectively a binary file. And Anvil gives you a way to package up binary files. See Files, Media and Binary Data. With this approach, you can handle images. The Media Object, received in the browser, can then be displayed directly in the UI via an Image or Link component
4 Likes
Thanks @p.colbert !
I tried
- Converting the image to a binary file
- 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