I want my app to enable users to upload an image and use that image for a specific function. The functions are defined in the server module. How do I read the image uploaded by the user in the server module using cv2.imread?
Hi there. Welcome to the forum!
Would something like this work?
I have not used the cv2 module before, but this allows you to get an image into Anvil, process it, and return it back to the client as downloadable media.
Try it out in a cloned app:
https://anvil.works/build#clone:V7UTES4HKZ7HUHGP=5COA6NSPAY4FRAGPV7YWH2ON
On the server-side:
import anvil.server
import cv2
import numpy as np
@anvil.server.callable
def process_image(my_media):
# read in image from media object
arr = np.fromstring(my_media.get_bytes(), np.uint8)
im = cv2.imdecode(arr, cv2.IMREAD_COLOR)
####
# add your processing here
####
# convert image to string and return downloadable media
im_str = cv2.imencode('.png', im)[1].tostring()
return anvil.BlobMedia("image/png", im_str, name='myimage.png')
On the client-side, the callback function for the FileLoader component could look like this:
def file_loader_1_change(self, file, **event_args):
"""This method is called when a new file is loaded into this FileLoader"""
my_media=self.file_loader_1.file
processed_image=anvil.server.call('process_image', my_media)
download(processed_image)
I hope this helps. Feel free to ask questions if anything is unclear.
4 Likes
Works smoothly. Thanks a lot.
1 Like
@campopianoa Thank you so much for this post! I have been trying to figure out how to get a media image file back to the client side for 2.5 days.
@ryan or anyone else at Anvil. Is there an easier way to go about this?
- seems like there must be an easier way to go from image to media object, but maybe not.