You are currently viewing the new Anvil Editor Docs.
Switch to the Classic Editor Docs
You are currently viewing the Classic Editor Docs.
Switch to the new Anvil Editor Docs

image module

API Docs

The image module allows you to manipulate images in your Anvil app. It is only available on the client side.

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(f"The image is {width} pixels wide and {height} pixels high")

Generating thumbnails

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

In order for generate_thumbnail() to work, the image itself will either need to allow for cross-origin access, or it will need to be loaded from your Anvil app. The image can be loaded from app assets, a HTTP endpoint or as a BlobMedia object.
# 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.

Do you still have questions?

Our Community Forum is full of helpful information and Anvil experts.