I’m currently working on a task. I’m taking input path of the folder containing multiple images from user and then successfully resizing them (by 200x200) using a python function. But i’m unable to display all the resized images in anvil forms.
Can you please help me in this problem? Currently i’m just able to display one image using anvil.BlobMedia. But i need “all of the resized images to display”.
Thank you so much for your response. I got your point and tried to improve my coding part as you said.
Since i’m new to anvil, i’m unable to do this part “[{‘image’:BlobMedia_object1}, …]” as you mentioned. I think i’m also making some mistakes in my python code on particularly this part.
Currently i’m getting this error, and unable to remove it:
from your code example I meant something more like this:
@anvil.server.callable
def task1(path):
ret = [] # empty array for storing images
for i in os.listdir(path):
img = tf.keras.preprocessing.image.load_img(path+'\\' +i, target_size=(200,200))
bs = io.BytesIO()
ret.append({'image' : anvil.BlobMedia('image/jpeg', bs)})
return ret
I think the main issue here is that you’re trying to access files on the User’s computer, but your Server Module code is running on the Anvil server, where there are no images at that path. You probably want to look at the FileLoader component, which lets users select files on their computer and upload them to Anvil. (In this case, it looks like you’ll want to make sure the multiple property is ticked, so they can select several files at once).
When the user has selected the files, you can pass them to the server. Something like this on the client:
def file_loader_1_change(self, files, **event_args):
# Pass the selected files to the server
results = anvil.server.call("process_files", files)
And something like this on the server:
import anvil.media
@anvil.server.callable
def process_files(files):
ret = [] # empty array for storing images
for f in files:
with anvil.media.TempFile(f) as file_name:
# Process the image
img = tf.keras.preprocessing.image.load_img(file_name, target_size=(200,200))
bs = io.BytesIO()
# TODO: Write the image bytes to `bs`
ret.append({'image' : anvil.BlobMedia('image/jpeg', bs)})
return ret
This is just an example - as noted in the code above, you will still need to actually get the bytes of the converted image. Alternatively, you could write the converted image to a temporary file, then convert that file to a Media Object you can return.