User-defined variables and arithmetic image transformations
Last updated: Sep-02-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.
- Arithmetic expressions enable you to assign values to a parameter or variable based on an arithmetic equation.
- User-defined variables enable you to keep value assignment separate from the transformation definition.
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 Use arithmetic operators to calculate shadow size](https://res.cloudinary.com/demo/image/upload/c_scale,w_300/e_shadow,x_w_div_50,y_w_div_50/docs/pizza_wine.jpg)
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.
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 metdata 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
orcolor
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
- Text overlays
- Image overlays
- Multiple string value comparisons
- Border and background color
- Self-referencing variables
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
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
- 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 Use a variable to set the border color](https://res.cloudinary.com/demo/image/upload/$bcolor_!red!/if_fc_gt_0/$bcolor_!rgb:374663!/if_end/c_fill,h_220,w_220/bo_5px_solid_$bcolor/docs/pepper.jpg)
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 Use a variable to set the border color](https://res.cloudinary.com/demo/image/upload/$bcolor_!red!/if_fc_gt_0/$bcolor_!rgb:374663!/if_end/c_fill,h_220,w_220/bo_5px_solid_$bcolor/docs/handbag4.jpg)
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,....
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 assigncurrent
to a variable,current
takes on the transformed pixel buffer at that point. If in the example above, we had first applied thee_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 theunique 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 variablex
is assigned the value5
only at the end of the transformation, that assignment will be applied first. Afterwards, thewidth
transformation takes on the value (5) of thex
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
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 Set width and aspect ratio using variables](https://res.cloudinary.com/demo/image/upload/$w_200/$ar_0.6/ar_$ar,c_fill,g_face,w_$w/docs/reporter.jpg)
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 Set width and aspect ratio using variables](https://res.cloudinary.com/demo/image/upload/e_trim/c_lpad,h_ih,w_iw/bo_4px_solid_green/c_scale,w_300/nice_bird.jpg)
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 Set width using arithmetic operators](https://res.cloudinary.com/demo/image/upload/$newwidth_10_add_iw_mul_0.3/c_scale,w_$newwidth/docs/mountains.jpg)
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:
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 text overlay with string variable](https://res.cloudinary.com/demo/image/upload/$award_!First!/$color_!rgb:FFFFFF!/$style_!Arial_150!/b_gray,co_$color,l_text:$style:%20%20$(award)%20%20Place%20,r_10,o_76,g_south,y_10/w_350,dpr_2/docs/green-race-car.jpg)
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:
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:
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 Add a PNG overlay](https://res.cloudinary.com/demo/image/upload/$overlay_ref:!docs:sale!/fn_wasm:docs:pnglayer.wasm/bo_1px_solid_black/w_300,dpr_2/docs/casual.jpg)
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.