Image resize on file uploader

Firstly, that AnvilWrappedError is caused by an old version of the anvil-uplink python library – please run pip install --upgrade anvil-uplink to get the latest version.


In a server module, you don’t need anvil.image because you can use full Python image processing libraries like Pillow. Conveniently, it’s already available in both our Python 2 and Python 3 server environments.

For your use-case, you’ll want to use the Image.resize function in a server module:

from PIL import Image
import io

@anvil.server.callable
def resize(file):
  # Convert the 'file' Media object into a Pillow Image
  img = Image.open(io.BytesIO(file.get_bytes()))
  
  # Resize the image to the required size
  img = img.resize((800,600))
  
  # Convert the Pillow Image into an Anvil Media object and return it
  bs = io.BytesIO()
  img.save(bs, format="JPEG")
  return anvil.BlobMedia("image/jpeg", bs.getvalue(), name=name)

Of course, you can do way more than that with the Pillow library. Do check it out.

Hope that helps!

4 Likes