Programmable Media

User-defined variables and arithmetic image transformations

Last updated: Dec-11-2024

You can add arithmetic and/or user-defined variables to your transformations. These expressions are evaluated on the fly, enabling you to add an additional layer of sophistication and flexibility to your transformations.

User-defined variables are especially valuable when used within named transformations. This enables complete separation of the transformation from the varying values used for delivery. This also makes it significantly easier to reuse common transformations for many assets, even when some specific adjustments must be made to the transformation depending on the specific asset or other data passed from another source.

You can achieve many complex transformation goals by using user-defined variables in conjunction with arithmetic expressions and conditional transformations.

See also: Variable and arithmetic video transformations.

Arithmetic expressions

You can create arithmetic expressions by using arithmetic operators with numeric transformation parameters or user-defined variables.

For example, you could set a relative shadow size for an image (the x and y of the e_shadow parameter) by setting these parameters to be equal to 2% of the current width of that image (w_div_50):

Use arithmetic operators to calculate shadow size

Note
When you use multiple arithmetic operators in an expression, standard order of operations apply (multiplication and division before addition and subtraction).

For example, iw_mul_2_add_ih_mul_2 would give you the perimeter measurement of the initial asset by first multiplying both the initial width by 2 and the initial height by 2, and then adding these two products.

Supported arithmetic operators

operation URL syntax SDK syntax
add add +
subtract sub -
multiply mul *
divide div /
modulo (remainder) mod %
pow
(to the power of)
pow ^

User-defined variables - overview

To use user-defined variables in your transformations, you first declare and assign values to the variables you want to use. In later components of your chained transformation, you can use the variables as the values of your transformation parameters.

Note
Not all transformation parameters are supported for use with variables. For details, see Variable types and supported parameters.

Variable naming

User-defined variables start with the $ sign, for example $newwidth. The name can include only alphanumeric characters and must begin with a letter.

Variable value types

Variables can be assigned a number value, string value, or they can take on the value of a numeric asset characteristic, such as iw (initial width) or fc (face count).

When working with string values:

  • String values are bounded by ! !.
  • To assign the value of an existing contextual metadata key to a variable, use the syntax: ctx:!key_name!. When you set a transformation parameter to that variable, it gets the value of the specified contextual metadata key.
  • To assign the value of a structured metadata ID to a variable, use the syntax: md:!external_id!. Be sure to use the external ID, not the label. When you set a transformation parameter to that variable, it gets the value of the specified metadata.
  • You can provide several values in a string using a colon : as the delimiter. For example: !string1:string2:string3!. These multiple-value strings can be used:

    • as separators for public IDs with slashes when the variable will be used to control the public ID of an overlay.
    • for comparing multiple values when the variable will be used in conjunction with the _in_ or _nin_ conditional transformation comparison operators.
    • to specify RGB Hex values for the border, background or color parameters. For example: !rgb:008000!.


    When a variable that is defined as a string value and contains a colon, is passed to any other parameter, the colon is treated as a literal character.

Assigning values to variables

Use the underscore to assign a value to a variable. For example:

  • $newwidth_200
  • $newheight_iw
  • $label_!sale!
  • $stringset_!string1:string2!

To convert a string value to a numeric value, append _to_i for an integer, or _to_f for a float. For example, to assign the value of the contextual metadata key, breadth, to the variable $newwidth:

  • as an integer, use the syntax: $newwidth_ctx:!breadth!_to_i
  • as a float, use the syntax: $newwidth_ctx:!breadth!_to_f

If assigning structured metadata to a variable, and the metadata type is numeric, you do not need to specify _to_i. For example, if you have a number field with external ID, position, you can use the syntax: $newwidth_md:!position!. However, if it is a text field you still need to append _to_i or _to_f to convert it to an integer or float.

Using arithmetic expressions with variables

You can use arithmetic operators with numeric variables just as you do with numeric transformation parameters, or even in combination. Consider this example:

$small_150/$big_2_mul_$small/c_fill,h_$small_add_20,w_$big

  • The $small variable is set to 150
  • The $big variable is assigned the value of 2 times the $small variable
  • The height parameter is set to use the value of $small plus 20
  • The width parameter is set to use the value of $big

Testing whether a variable has been defined

You can test whether or not a variable has been defined using the parameters if_isdef_$<variable name> and if_isndef_$<variable name>.

For example, check if the $big variable has been defined, and if so, set the width:

if_isdef_$big/c_scale,w_$big/if_end

Similarly, if the $small variable is not defined, set it to a default value:

if_isndef_$small/$small_300/if_end

Learn more about conditional transformations.

Variable types and supported parameters

User-defined variables for images support the following variable types and parameters:

Numeric variables

You can apply a numeric variable value to the following transformation parameters:

  • w (width)
  • h (height)
  • x, y
  • q (quality)
  • if
  • ar (aspect_ratio)
  • a (angle)
  • z (zoom)
  • o (opacity)
  • r (radius)
  • dpr
  • e (effect): for the numeric strength value of an effect. For example: $strength_50/e_hue:$strength
  • bo (border): for the numeric pixel width of the border. For example: $pixwidth_w_mul_0.1/bo_$pixwidth_solid_white
    Note that even though the syntax for directly setting the border width is usually a string element (e.g. 7px), when you want to pass the value as a variable, you pass it as a number value and not a string.

Use-case example: Set width and aspect ratio using variables

String variables

You can apply a string variable for the following:

Effects

You can use a variable for the name and/or any value of an effect. For example:

  • $effect_!brightness!/e_$effect:60
  • $artfilter_!incognito!/e_art:$artfilter
  • $firstcolor_!red!/$secondcolor_!008000!/e_tint:50:$firstcolor:$secondcolor

Note
Some effects allow you to specify arrays of strings, for example, the prompt parameter of the gen_recolor effect. Variables cannot currently be used in arrays.

Text overlays

You can use a variable for all or part of the text value in a text overlay.

To mix static text with a string variable when specifying a text overlay, use the syntax: static text $(variable) more static text. For example:

  • $name_!Max!/l_text:arial_10:My name is $(name) the Magnificent/fl_layer_apply

You can also use variables for the text style and color. For example:

  • $style_!Arial_12!/$color_!rgb:ff33cc!/co_$color,l_text:$style:hello/fl_layer_apply

Use-case example: Text overlay with string variable

Image overlays

You can use a variable for the public ID of an image overlay. For example:

$overlay_!sample!/c_fill,h_400,w_400/l_$overlay/c_scale,w_100/fl_layer_apply,g_south_east,x_20,y_20

Important
  • If the public ID for the overlay includes slashes, replace the slashes with colons. For example, the same transformation from above, but overlaying 'mypath/myimage': $overlay_!mypath:myimage!/c_fill,h_400,w_400/l_$overlay/c_scale,w_100/fl_layer_apply,g_south_east,x_20,y_20
  • To use a variable with authenticated overlays, include the authenticated string as part of the variable as well, for example: .../$overlay_!authenticated:donotdelete:ueezkavitxmcnsdpavzi!/l_$overlay,w_600/...

Use-case example: Image overlay variable in a named transformation

Border and background color

You can use a variable to set the color of a border (bo in URLs) or background (b in URLs) to either a color name or an RGB Hex value. For RGB hex values, use the syntax $var_!rgb:######!.

For example, the following transformation sets the variable $bcolor to red. Afterwards, a condition checks whether the image has at least one face (face_count > 0), and if so, it changes the $bcolor variable value to a specific shade of blue (#374663). Lastly, the image is given a border whose color is determined by the $bcolor variable.

Use a variable to set the border color

 

Using the identical transformation on an image with at least one face applies the defined blue color for the border:

Use a variable to set the border color

Multiple string value comparisons

You can use a variable when verifying that all of the specified values are (or are not) contained within another set of values. For example:

$mystringset_!string1:string2:string3!/if_$mystringset_in_tags,....

Note
When you use variable or conditional expressions that include the tags, ctx or md parameters, their values are exposed publicly in the URL. If you want to prevent such values from being exposed, you can disable the Usage of tags/context/metadata in transformation URLs option in the Security Settings (enabled by default). When this setting is disabled, any URL that exposes tags, contextual metadata or structured metadata values will return an error.

File reference variables

You can send additional files to a Custom function by passing them as a base64 encoded string using reference variables. These variables are passed to WebAssembly and remote functions through a JSON metadata structure together with contextual metadata and tags, as explained in the Custom functions documentation.

To define a reference variable, insert ref: before the value of the variable. For example:

$file_ref:!myfile!/fn_wasm:my_example.wasm

In the above example, myfile can be the public ID of any file stored in Cloudinary or a URI. If the public ID includes slashes, replace the slashes with colons. For example, to reference 'path1/path2/myfile', use:

$file_ref:!path1:path2:myfile!/fn_wasm:my_example.wasm

Use-case example: Pass a PNG file to a WebAssembly function to use as an overlay

Self-referencing variables

You can set a user-defined variable to current to refer to the image being delivered in the current URL. This enables you to use the image being delivered as the value for other transformations without needing to know the image's public_id when you are building the transformation. This also enables you to reference the delivered image from within a named transformation.

For example: $img_current/e_grayscale/l_$img/bo_30px_solid_white/c_scale,w_0.3/fl_layer_apply,g_north_west

This will cause the delivered grayscale image to also be used as a color overlay, in this case, displayed at the top left with a white border:

There are two ways to use the current variable.

  • pixel buffer: The default current represents the actual current pixel buffer. This means that if you apply transformations to the delivered image and then assign current to a variable, current takes on the transformed pixel buffer at that point. If in the example above, we had first applied the e_grayscale transformation, and in the next component of the chain, we defined $img_current, and following that applied the $img variable as an overlay, the overlay would get the transformed grayscale image.
  • public_id: You can alternatively assign a variable to current:public_id. This captures the unique identifier of the original asset (type, resource type and public ID) as a string. You can pass this value to an image overlay or underlay parameter if you want to reference the original image, regardless of where it is defined in the transformation chain.

Use-case example: Use a self-referencing variable to create a blurred padding background

Expression evaluation order

Within a transformation component, condition (if) statements are evaluated first, then variable assignments, then transformations. Therefore:

  • When an assignment is made in a conditional component, the assignment is evaluated only if the condition is true.

  • Even if a transformation is specified before a variable assignment within the same URL component, the value is assigned before the transformation. For example, if you deliver a URL containing the following condition:
    if_w_gt_5,w_$x,$x_5
    Even though the variable x is assigned the value 5 only at the end of the transformation, that assignment will be applied first. Afterwards, the width transformation takes on the value (5) of the x variable.

However, the best practice is to separate conditions from results in separate URL components in the order you want them evaluated. For example: if_w_gt_5/$x_5/c_scale,w_$x/if_end, as explained in Conditional transformations.

Use-case example: Set height based on aspect ratio

Use-case examples

Note
For purposes of simplicity, most of these examples do not use named transformations. However, in reality, you will often get the most value from variables when used with named transformations.

Simple

Set the variable $w to 200, and the $ar parameter to 0.56 (9:16). Then set aspect ratio parameter to the $ar value and the width parameter to the $w value, along with face-based fill cropping:

Set width and aspect ratio using variables


Use the initial height and width (c_lpad,h_ih,w_iw) to center an object in an image after trimming (e_trim):

Set width and aspect ratio using variables

Arithmetic

Create a new variable called $newwidth. Set the value of the variable to be the image's initial width multiplied by 0.3 (according to that standard order of operations), and then add 10. Resize the image by setting the width parameter to the $newwidth value:

Set width using arithmetic operators

Conditional

Check whether the image has portrait orientation (aspect ratio < 1). If so, set the $height variable to 300. Otherwise set the $height variable to 200. Then set the height of the delivered image to be the assigned $height value:

landscape orientation landscape orientation portrait orientation portrait orientation

Text overlay

Set the variable $award to the string value !First!. Then set the text overlay to use the text $(award) Place. The style and color of the text are also set using variables ($style and $color). The text overlay is placed near the bottom of the image on a semi-transparent, rounded border.

text overlay with string variable

Named transformation

In a named transformation called passport_photo, define the cropping for an image to be a 70% zoomed thumbnail with face detection, using a variable for the width and height, where height is relative to width, to get the legal 3.5x4.5 (0.78) ratio. There is also a white border with a gray edge that emulates a printed photo border.

Named transformation definition:

c_thumb,g_face,h_$width_div_0.78,w_$width,z_0.6/bo_13px_solid_white/bo_2px_solid_gray

In the delivery URL code, you define the value for the width parameter, which is applied to the named transformation to yield a printable passport photo of the desired size:

width = 115 pixels width = 115 pixels width = 140 pixels width = 140 pixels width = 165 pixels width = 165 pixels

The 3 images above use essentially identical delivery URLs, each calling the same named transformation, only with different values assigned to the $width variable: 115, 140, or 165.

Image overlay in a named transformation

Create a named transformation called image_ratings with the following definition:
c_fill,h_400,w_400/l_$rating/c_scale,w_100/fl_layer_apply,g_south_east,x_20,y_20

The image overlay is defined as a variable called rating. You can then assign the variable value with either the thumbs-up or thumbs-down image to display the rating for a particular image. For example:

Thumbs-up rating Thumbs-up rating Thumbs-down rating Thumbs-down rating

File reference variable

Pass the asset with public ID: docs/sale.png, to the WebAssembly function with public ID: docs/pnglayer.wasm, as a reference variable called overlay. The PNG file is overlaid on the casual.jpg image.

This is the generated URL:

Add a PNG overlay

Here is the Rust code that was compiled to pnglayer.wasm. Notice how the variable called overlay is obtained in the code variables.get("overlay"):

Self-referencing variable

Check whether the image width is less than 800 pixels. If so, add a blurred, increased-brightness version of the current image behind the delivered image. The blurred image will be 800 pixels wide and the same height as the original image.

Add blurred underlay padding for the current image

✔️ Feedback sent!

Rate this page: