Self-referencing variables in transformations

JackieDoc Member, Cloudinary Staff Posts: 3
edited August 2022 in Developer APIs

There are lots of times when you might want to overlay (or underlay) a different transformation of the same image.

For example, you might want to have a small, cropped and zoomed version of a product as a layer over a full sized image of a product, or you might want a blurred landscape version of a picture as the background (underlay) for a portrait photo.

Did you know that you can use self-referencing variables in your transformations to accomplish this at scale for any image? In other words, you can set your transformation to automatically use whatever the base image's public ID is also for your overlay or underlay image.

To do this, just set a user-defined variable (such as $img) to the value current and then pass that user-defined variable instead of a public_id to your overlay or underlay.

Here are a couple nice examples:$img_current/e_grayscale/l_$img/c_thumb,w_0.4,g_auto/bo_5px_solid_white/fl_layer_apply,g_north_east/c_scale,w_900/f_auto/q_auto/docs/handbag_640.jpg$img_current/$height_ih/if_w_lt_1300/u_$img/c_scale,h_$height,w_1300/e_blur:1300/e_brightness:40/fl_layer_apply/if_end/docs/pic9

(This one also uses a conditional transformation, so that the self-referencing underlay will only get added in case the base image's width is less than than the overall image width you want to deliver)

Since these transformations are using variables, you can save these transformations as named transformations and then use them on any image in your account!


There are so many applications for self-referencing variables. Have you ever implemented one? Or did this post get you trying out some ideas?

We'd love to see some more cool implementations of self-referencing variables. Please share yours below for your fellow developers to enjoy!