Live Chat

We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.

If you don't want to do this, you can email us instead at contact@anvil.works.

image module

API Docs

The image module allows you to manipulate images in your Anvil app. Begin by importing the anvil.image module.

Get dimensions

To get the width and height of an image, use get_dimensions:

import anvil.image

# The image can be any Media object containing an image
image_media = URLMedia('https://anvil.works/img/workshops-cogwheels.jpg')

width, height = anvil.image.get_dimensions(image_media)

print("The image is %s pixels wide and %s pixels high" % (width, height))

Generating thumbnails

To generate a thumbnail of an image (for uploading, for example) use the generate_thumbnail method.

# Resize the image to have a maximum dimension of 120px.
small_img = anvil.image.generate_thumbnail(image_media, 120)

Rotating

To rotate an image clockwise by some number of degrees, use the rotate method. The rotate method works on images uploaded to your app, but will not work for third-party images. See below for more information.

# Get the 'forest.jpg' image previously uploaded to Assets
my_image = "_/theme/forest.jpg"
image_media = URLMedia(my_image)

# Rotate the image by 90 degrees.
rotated_img = anvil.image.rotate(image_media, 90)
self.image_1.source = rotated_img

It’s not possible to rotate a cross-origin image. Browsers don’t allow you to access the raw bytes of a third-party image from code, for security reasons. This is true in any application.

For this reason, anvil.image.rotate will not work on third party images.

Display mode

To configure how the image is displayed, use the display_mode property. This determines how the size of the image should be adjusted to fit the size of the Image component.

The available options are:

  1. shrink_to_fit - (default) - this shrinks or grows the image to the smaller of the width or height of the Image component.
  2. fill_width - this shrinks or grows the image until it fills the width of the Image component, and determines the height from that.
  3. original_size - this displays the image at whatever the browser thinks the original size is. If that would cause the image to be wider than the Image component, it shrinks the image to ensure it fits within the width of the Image component.