image module allows you to manipulate images in your Anvil app. Begin by importing the
To get the width and height of an image, use
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))
To generate a thumbnail of an image (for uploading, for example) use the
# Resize the image to have a maximum dimension of 120px. small_img = anvil.image.generate_thumbnail(image_media, 120)
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.
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:
shrink_to_fit- (default) - this shrinks or grows the image to the smaller of the width or height of the Image component.
fill_width- this shrinks or grows the image until it fills the width of the Image component, and determines the height from that.
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.