ImageTransform

View as Markdown

ImageTransform

The Image Delivery API resizes, crops, and converts the images in a stack when a client requests an image URL with query parameters. Use this class to

  • hold an image URL together with the Image Delivery API parameters you want on it
  • read the finished URL as a string

Create an instance with the image_transform method of Stack, which takes the arguments below:

NameTypeDescription
image_urlstrURL of the image, such as the url of an asset.
kwargsAnyImage Delivery API parameters, one keyword argument each.

Warning logger is a named argument of the ImageTransform constructor. stack.image_transform(url, logger=my_logger) sets the logger of the instance and adds no logger parameter to the URL.

Class-Level Notes

This class makes no request.

  • get_url builds a string. No method of this class opens a connection, so none returns a response or an error_code.
  • The timeout, retry, and region settings of the Stack have no effect here.
  • The Image Delivery API applies the parameters when a browser or HTTP client requests the finished URL. It reports any rejection to that client, not to the SDK.

The SDK checks no parameter.

  • image_transform raises PermissionError only when image_url is None or an empty string.
  • The SDK accepts any parameter name and any value, and writes both into the URL. A misspelled name reaches the URL unchanged.
  • A parameter whose name has a hyphen, such as bg-color, is not a valid Python keyword. Pass it by unpacking a dictionary: **{'bg-color': 'FFFFFF'}.
  • Pass a value with several parts, such as a crop region, as one string: crop='300,400'. The SDK converts other values with str(), so the tuple (300, 400) reaches the URL as (300, 400).

Environment.

  • The Image Delivery API reference lists environment as a query parameter of every image request. get_url does not add it. Pass environment='<ENVIRONMENT>' as a keyword argument to include it.

Image Delivery API parameters. The table below lists the parameters the Image Delivery API accepts, with the values its reference gives:

ParameterPass asAccepted valuesAPI reference
widthwidth=6401 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with p such as 300pWidth
heightheight=4801 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with p such as 300pHeight
disabledisable='upscale'upscale, the only valueDisable
fitfit='bounds', with width and heightbounds, cover, or cropFit Mode
cropcrop='300,400'Width and height in pixels or percentage, an aspect ratio such as 1:3, with optional x, y, offset-x, offset-y, safe, or smart partsCrop
trimtrim='25,50,75,100'Top, right, bottom, and left edges in pixels or percentageTrim
canvascanvas='700,800'Width and height in pixels or percentage, or an aspect ratio such as 2:3Canvas
padpad='25,50,75,100'Top, right, bottom, and left padding in pixels or percentage. The API ignores pad when canvas is presentPad
bg-color**{'bg-color': 'cccccc'}A 3 or 6 digit hexadecimal value, an RGB value such as 140,220,123, or an RGBA value such as 140,220,123,0.5Background Color
dprdpr=2, with width or height1 to 10000, or 0.0 to 9999.9999Device Pixel Ratio
resize-filter**{'resize-filter': 'lanczos3'}, with width or heightnearest, bilinear, bicubic, lanczos2, or lanczos3Resize-filter
formatformat='webp'auto, gif, png, jpg, pjpg, webp, webpll, webply, or avifFormat
autoauto='webp'webp or avif. Does not apply to GIF filesAuto
qualityquality=801 to 100. Applies to lossy formats onlyQuality
orientorient=61 to 8, from default orientation to a 90 degree left rotationOrientation
frameframe=11, the first frame of an animated GIFFrame
blurblur=401 to 1000Blur
brightnessbrightness=20-100 to 100Brightness
contrastcontrast=20-100 to 100Contrast
saturationsaturation=20-100 to 100Saturation
sharpensharpen='a2,r1000,t2'Amount a, radius r, and threshold tSharpen
overlayoverlay='<OVERLAY_RELATIVE_URL>'Relative URL of the image to place on topOverlay
overlay-align**{'overlay-align': 'left,bottom'}top, bottom, left, right, middle, center, or two of them. Defaults to middle,centerOverlay Align
overlay-repeat**{'overlay-repeat': 'x'}x, y, or bothOverlay Repeat
overlay-width**{'overlay-width': 200}1 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with pOverlay Width
overlay-height**{'overlay-height': 200}1 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with pOverlay Height
overlay-pad**{'overlay-pad': '30,25,50'}Top, right, bottom, and left padding of the overlayOverlay Pad

Capability Matrix

CapabilitySupportedNotes / Alternative
Download the resized or converted imageNoget_url returns a string. Request it with your own HTTP client
Check a parameter name or valueNoThe Image Delivery API judges the parameters when a client requests the URL
Percent-encode a parameter valueNoEncode the value with urllib.parse.quote before you pass it
Build two URLs from one instanceNoCreate one instance per URL, and call get_url once on it
Change a parameter after constructionNoPass the full set to stack.image_transform

Method Index

Read the finished URL. Available on every instance that stack.image_transform() returns.

Method NameReturnsDescription
get_urlThe image URL followed by its transformation parameters.Builds the image URL with its query parameters.

Class-Level Snippet

This snippet reads an asset, then builds a 640-pixel WebP thumbnail URL with a white padded border from its url.

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

try:
    result = stack.asset('<ASSET_UID>').fetch()
except Exception as error:
    # Raised only for network failures (timeout, DNS error, dropped connection)
    print('Request failed:', error)
else:
    if 'error_code' in result:
        # The Delivery API rejected the request and returned the error body
        print('Delivery API error:', result['error_code'], result['error_message'])
    else:
        thumbnail = stack.image_transform(
            result['asset']['url'],
            width=640,
            format='webp',
            quality=80,
            pad='10',
            environment='<ENVIRONMENT>',
            **{'bg-color': 'FFFFFF'},
        )
        # get_url builds the string and makes no request.
        print(thumbnail.get_url())

Methods

Each method of the ImageTransform class has its own section below, with its parameters, validation rules, behavior, and examples.

get_url

get_url returns the image URL with each transformation parameter appended as a query parameter.

This method takes no parameters. It reads the image URL and the keyword arguments you passed to image_transform.

Returns: str. The image URL followed by its transformation parameters.

Validation

  • There is no client-side validation. get_url writes every parameter name and value into the URL as given, and the Image Delivery API judges them when a client requests the URL.
  • get_url raises TypeError when the image URL is not a string and at least one parameter exists, because it appends text to the URL.

Behavior

  • Client-side only. get_url makes no request.
  • It returns <image_url>?name=value&name=value, with the parameters in the order you passed them. Without parameters, it returns the image URL unchanged.
  • The SDK converts each value with str(), so None reaches the URL as None. Leave out a parameter you do not need rather than passing None.
  • get_url does not percent-encode values. A space stays a space, and an & inside a value starts a new parameter. Encode such a value with urllib.parse.quote before you pass it.
  • Known issue: In 2.8.1, each call appends the parameters to the stored URL again. A second call on the same instance returns a URL with two query strings. Call get_url once per instance and keep the string.
  • Known issue: In 2.8.1, get_url always joins with ?, so an image URL that already has a query string gets a second ?. Pass the existing query parameters as keyword arguments, with the base URL alone as image_url.

Example

Basic usage: a resized WebP URL

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

image_url = 'https://images.contentstack.io/v3/assets/<API_KEY>/<ASSET_UID>/<FILE_UID>/hero.jpg'

try:
    transform = stack.image_transform(image_url, width=640, height=480, format='webp')
except PermissionError as error:
    # Fires when image_url is None or an empty string
    print('Provide an image URL:', error)
else:
    url = transform.get_url()
    print(url)

Several URLs: one instance per URL

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

image_url = 'https://images.contentstack.io/v3/assets/<API_KEY>/<ASSET_UID>/<FILE_UID>/hero.jpg'

sizes = [320, 640, 1280]
urls = {}
for width in sizes:
    # A new instance for each size, and one get_url call on each.
    urls[width] = stack.image_transform(image_url, width=width, fit='bounds', height=width).get_url()

for width, url in urls.items():
    print(width, url)

Edge case: encode a value that holds reserved characters

from urllib.parse import quote

import contentstack

stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>')

image_url = 'https://images.contentstack.io/v3/assets/<API_KEY>/<ASSET_UID>/<FILE_UID>/hero.jpg'
overlay = '/v3/assets/<API_KEY>/<OVERLAY_ASSET_UID>/<OVERLAY_FILE_UID>/logo & badge.png'

# get_url writes values as given, so encode the overlay path first.
url = stack.image_transform(
    image_url,
    overlay=quote(overlay),
    **{'overlay-align': 'right,bottom'},
).get_url()
print(url)