ImageTransform
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:
| Name | Type | Description |
|---|---|---|
| image_url | str | URL of the image, such as the url of an asset. |
| kwargs | Any | Image 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:
| Parameter | Pass as | Accepted values | API reference |
|---|---|---|---|
| width | width=640 | 1 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with p such as 300p | Width |
| height | height=480 | 1 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with p such as 300p | Height |
| disable | disable='upscale' | upscale, the only value | Disable |
| fit | fit='bounds', with width and height | bounds, cover, or crop | Fit Mode |
| crop | crop='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 parts | Crop |
| trim | trim='25,50,75,100' | Top, right, bottom, and left edges in pixels or percentage | Trim |
| canvas | canvas='700,800' | Width and height in pixels or percentage, or an aspect ratio such as 2:3 | Canvas |
| pad | pad='25,50,75,100' | Top, right, bottom, and left padding in pixels or percentage. The API ignores pad when canvas is present | Pad |
| 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.5 | Background Color |
| dpr | dpr=2, with width or height | 1 to 10000, or 0.0 to 9999.9999 | Device Pixel Ratio |
| resize-filter | **{'resize-filter': 'lanczos3'}, with width or height | nearest, bilinear, bicubic, lanczos2, or lanczos3 | Resize-filter |
| format | format='webp' | auto, gif, png, jpg, pjpg, webp, webpll, webply, or avif | Format |
| auto | auto='webp' | webp or avif. Does not apply to GIF files | Auto |
| quality | quality=80 | 1 to 100. Applies to lossy formats only | Quality |
| orient | orient=6 | 1 to 8, from default orientation to a 90 degree left rotation | Orientation |
| frame | frame=1 | 1, the first frame of an animated GIF | Frame |
| blur | blur=40 | 1 to 1000 | Blur |
| brightness | brightness=20 | -100 to 100 | Brightness |
| contrast | contrast=20 | -100 to 100 | Contrast |
| saturation | saturation=20 | -100 to 100 | Saturation |
| sharpen | sharpen='a2,r1000,t2' | Amount a, radius r, and threshold t | Sharpen |
| overlay | overlay='<OVERLAY_RELATIVE_URL>' | Relative URL of the image to place on top | Overlay |
| overlay-align | **{'overlay-align': 'left,bottom'} | top, bottom, left, right, middle, center, or two of them. Defaults to middle,center | Overlay Align |
| overlay-repeat | **{'overlay-repeat': 'x'} | x, y, or both | Overlay Repeat |
| overlay-width | **{'overlay-width': 200} | 1 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with p | Overlay Width |
| overlay-height | **{'overlay-height': 200} | 1 to 8192 pixels, 0.0 to 0.99 for a percentage, or a value with p | Overlay Height |
| overlay-pad | **{'overlay-pad': '30,25,50'} | Top, right, bottom, and left padding of the overlay | Overlay Pad |
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Download the resized or converted image | No | get_url returns a string. Request it with your own HTTP client |
| Check a parameter name or value | No | The Image Delivery API judges the parameters when a client requests the URL |
| Percent-encode a parameter value | No | Encode the value with urllib.parse.quote before you pass it |
| Build two URLs from one instance | No | Create one instance per URL, and call get_url once on it |
| Change a parameter after construction | No | Pass the full set to stack.image_transform |
Method Index
Read the finished URL. Available on every instance that stack.image_transform() returns.
| Method Name | Returns | Description |
|---|---|---|
| get_url | The 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)