Image resize on file uploader

I’m using your file uploader to upload pictures from people’s phones. During my testing I’ve uploaded about 11 and hit my database quota. Do you have anything you could recommend to work with your media objects to reduce the file size? They probably don’t need to be as big as they are.

Absolutely - you want the anvil.image module, and specifically anvil.image.generate_thumbnail().

Documentation here :slight_smile:

1 Like

Will this work in a server module?

I’m trying to write a script to go through the files I’ve already put in the database, see how big they are, try making them smaller using the code above, and then looking at the new size. But I’m getting all sorts of errors.

for row in rows:
    print(row['file'].name)
    print(row['file'].content_type)

works just fine. But

print(row['file'].length)

gives the error:

anvil._server.AnvilWrappedError: Exception: 'No server function matching "fetch_lazy_media" has been registered'

and then if I try:

import anvil.images

I get:

ModuleNotFoundError: No module named 'anvil.images'

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

Works beautifully. I’ll have a play with pillow!

A post was split to a new topic: OSError: cannot write mode RGBA as JPEG