React Native image transformations
Last updated: May-20-2024
Overview
After you or your users have uploaded image assets to Cloudinary, you can deliver them via dynamic URLs. You can include instructions in your dynamic URLs that tell Cloudinary to transform your assets using a set of transformation parameters. All transformations are performed automatically in the cloud and your transformed assets are automatically optimized before they are routed through a fast CDN to the end user for optimal user experience.
For example, you can resize and crop, add overlay images, blur or pixelate faces, apply a large variety of special effects and filters, and apply settings to optimize your images and to deliver them responsively.
The @cloudinary/url-gen
package simplifies the generation of transformation URLs, and includes special components and directives for easy embedding of assets in your React Native application.
Image transformations with React Native
To transform an image asset, use the @cloudinary/url-gen
package to create the transformation, then pass the transformed image object to the cldImg
attribute in your AdvancedImage
component to load the image in your app. For example:
import React from 'react';
import { SafeAreaView } from 'react-native';
import { AdvancedImage } from 'cloudinary-react-native';
import { Cloudinary } from "@cloudinary/url-gen";
// Import required actions and qualifiers.
import { thumbnail } from "@cloudinary/url-gen/actions/resize";
import { byRadius } from "@cloudinary/url-gen/actions/roundCorners";
import { focusOn } from "@cloudinary/url-gen/qualifiers/gravity";
import { FocusOn } from "@cloudinary/url-gen/qualifiers/focusOn";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
export default function App() {
// Use the image with public ID, 'front_face'.
const myImage = cld.image('front_face');
// Apply the transformation.
myImage
.resize(thumbnail().width(150).height(150).gravity(focusOn(FocusOn.face()))) // Crop the image, focusing on the face.
.roundCorners(byRadius(20)); // Round the corners.
// Render the transformed image in a React component.
return (
<SafeAreaView style={{flex: 1, justifyContent: 'center'}}>
<AdvancedImage cldImg={myImage} style={{ width: 200, height: 200, alignSelf: 'center'}} />
</SafeAreaView>
)
};
In the above example, the front_face image is cropped to a 150 x 150 pixel thumbnail with rounded corners, focusing on the face, resulting in this URL:
The @cloudinary/url-gen
package installs an additional transformation-builder-sdk library as a dependency, which handles the transformation generation part of the URL.
You can use the Transformation Builder reference to find all available transformations, syntax and examples.
Alternative ways to apply transformations
There are a couple of other ways to apply transformations to your images that you may prefer to use, for example if a new transformation is not yet supported by the SDK, or if you're more familiar with other SDKs. Note, however, that you won't benefit from your IDE's code completion feature for building the transformations in these ways.
See also: Shortcuts and aliases for other ways to simplify the syntax.
URL syntax
You can add any transformation in URL syntax using the addTransformation
method.
For example:
myImage.addTransformation('c_thumb,g_face,h_150,w_150/r_20');
This can be used together with other actions and qualifiers in the usual way. It's useful if a new transformation is added but not yet available in the SDK, or if you're just more familiar with the URL syntax.
Object syntax
If you prefer the more concise syntax used for transformations in the Node.js SDK, you can use the transformationStringFromObject
method to build the transformation, and add it to your image using addTransformation
, importing only transformationStringFromObject
instead of all the individual actions and qualifiers.
For example:
import { transformationStringFromObject } from "@cloudinary/url-gen";
const transformation = transformationStringFromObject([
{gravity: "face", height: 150, width: 150, crop: "thumb"},
{radius: 20}
]);
myImage.addTransformation(transformation);
Syntax overview
The @cloudinary/url-gen
package provides an intuitive coding experience for transforming an asset:
- The SDK supports an action-based syntax, designed to make building delivery URLs and transformations logical and discoverable.
- It allows discovering the available options from within your development environment, and ensures that only options that are supported can be used together.
The general form of the syntax is:
An example being:
Actions and ActionGroups
- Assets expose methods called ActionGroups (
myImage.adjust()
) that represent a directive to Cloudinary on how to transform a specific aspect of an asset - ActionGroups receive an Action object as a parameter that defines the specific action to apply
- Action objects are created through Factory methods (
Adjust.replaceColor()
) - Some actions require a qualifier as a parameter (
lightblue
) - You can find more Actions in
@cloudinary/url-gen/actions
- You can import all actions with
import {Actions} from '@cloudinary/url-gen'
Qualifiers and QualifierValues
- Actions expose methods to define their behaviors (
tolerance()
) - We call the methods on Actions, Qualifiers
- Qualifiers usually accept a QualifierValue (
17
intolerance(17)
) - QualifierValues can be primitive (numbers, strings) or predefined SDK values that can be imported
- Many QualifierValues are functions
- You can find more QualifierValues in
@cloudinary/url-gen/qualifiers
The output of each ActionGroup is a complete transformation component (separated by slashes) in the URL. For example, the syntax example above would generate the following URL:
Tree shaking
The @cloudinary/url-gen
package allows you to import only what you need, to minimize your bundle size.
See the Transformation Builder reference for all actions and qualifiers.
For example, if you import Effect
, you import all effect actions, which may be more than you need. The only reason you may want to do this is to make other methods discoverable. Without tree shaking, actions require qualification (for example, Effect.outline()
).
-
Without tree shaking:
JSimport {Effect} from "@cloudinary/url-gen/actions/effect"; // Effect.outline()
You can also use:
JSimport {Effect} from "@cloudinary/url-gen/actions/effect"; const {outline} = Effect; // outline()
In this case
outline()
is equivalent toEffect.outline()
. -
With tree shaking:
JSimport {outline} from '@cloudinary/url-gen/actions/effect'; // outline()
Similarly, for qualifier values:
-
Without tree shaking:
JSimport {OutlineMode} from "@cloudinary/url-gen/qualifiers/outlineMode"; // OutlineMode.outer()
-
With tree shaking:
JSimport {outer} from "@cloudinary/url-gen/qualifiers/outlineMode"; // outer()
Most of the examples shown in this guide use tree shaking.
Shortcuts and aliases
To simplify some of the syntax, you can use string shortcuts for nested qualifiers. For example, rather than:
myImage.delivery(Delivery.format(Format.jpg());
you can say:
myImage.delivery(Delivery.format('jpg'));
Additionally, there are aliases for delivery format and quality, to shorten the syntax further. For example, the above can be shortened to:
myImage.format('jpg');
For quality, instead of:
myImage.delivery(Delivery.quality('auto'));
you can say:
myImage.quality('auto');
Deliver and transform images
The @cloudinary/url-gen
package makes it easy for you to create image URLs including any transformation parameters.
Direct URL building
You can build an image URL by:
- Configuring your Cloudinary instance.
- Instantiating a
CloudinaryImage
object for the image you want to deliver, usingcld.image()
.
- Calling the
toURL()
method of theCloudinaryImage
object to return the delivery URL:
import {Cloudinary} from "@cloudinary/url-gen";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Instantiate a CloudinaryImage object for the image with public ID, 'sample'.
const myImage = cld.image('sample');
// Return the delivery URL
const myUrl = myImage.toURL();
The resulting URL, myURL
, is:
Specifying a version of your image to deliver
You can specify a particular version of your image to deliver by using the setVersion
method. The version is added to the delivery URL as explained in Asset versions.
For example, to specify version 1610625835
of the sample image from the example above:
myImage.setVersion(1610625835);
The resulting URL is now:
Specifying the delivery type
You can change the delivery type from the default of upload
to any of the other delivery types, using the setDeliveryType
method.
For example, to define a fetch
URL:
const myImage = cld.image('https://upload.wikimedia.org/wikipedia/commons/1/13/Benedict_Cumberbatch_2011.png').setDeliveryType('fetch');
The resulting URL is:
Transforming your image
Images are transformed by adding serialized transformation instructions to the image delivery URL. For example, to scale your image to a width of 400 pixels, add c_scale,w_400
.
https://res.cloudinary.com/demo/image/upload/c_scale,w_400/bike.jpg
Using the @cloudinary/url-gen
package, you transform an image by performing one or more transformation actions on the CloudinaryImage
object (see the syntax overview). Remember to import the actions that you are using:
import {Cloudinary} from "@cloudinary/url-gen";
// Import the scale mode from the resize action.
import {scale} from "@cloudinary/url-gen/actions/resize";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'bike'.
const myImage = cld.image('bike');
// Scale the image to a width of 400 pixels.
myImage.resize(scale().width(400));
Chaining transformations
Cloudinary transformations can be chained together (each transformation is applied to the result of the previous transformation). For example, the following code crops the image to 150x150, rounds the corners, applies a sepia effect, adds text to the top center of the resized image, then rotates the entire result by 20 degrees and delivers a PNG.
import {Cloudinary} from "@cloudinary/url-gen";
// Import required actions.
import {fill} from "@cloudinary/url-gen/actions/resize";
import {source} from "@cloudinary/url-gen/actions/overlay";
import {byAngle} from "@cloudinary/url-gen/actions/rotate"
import {sepia} from "@cloudinary/url-gen/actions/effect";
import {byRadius} from "@cloudinary/url-gen/actions/roundCorners";
// Import required values.
import {text} from "@cloudinary/url-gen/qualifiers/source";
import {Position} from "@cloudinary/url-gen/qualifiers/position";
import {TextStyle} from "@cloudinary/url-gen/qualifiers/textStyle";
import {compass} from "@cloudinary/url-gen/qualifiers/gravity";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'sample'.
const myImage = cld.image('sample');
// Transform the image.
myImage
.resize(fill(150, 150))
.roundCorners(byRadius(20))
.effect(sepia())
.overlay(
source(
text('This is my picture', new TextStyle('arial',18))
.textColor('white')
)
.position(new Position().gravity(compass('north')).offsetY(20)))
.rotate(byAngle(20))
.format('png');
// Return the delivery URL
const myUrl = myImage.toURL();
The code above generates the following image delivery URL:
Apply common image transformations
This section provides an overview and examples of how to implement the following commonly used image transformation features using the @cloudinary/url-gen
package.
- Resizing and cropping
- Converting to another image format
- Applying image effects and filters
- Adding text and image overlays
- Image optimizations
Keep in mind that this section is only intended to introduce you to the basics of using image transformations.
- For comprehensive explanations of how to implement a wide variety of transformations, see Image transformations.
- For a full list of all supported image transformations and their usage, see the Transformation URL API reference.
Resizing and cropping
There are a variety of different ways to resize and/or crop your images, and to control the area of the image that is preserved during a crop. The following example uses the fill
cropping method to generate and deliver an image that completely fills the requested 250x250 size while retaining the original aspect ratio. It uses face detection gravity to ensure that all the faces in the image are retained and centered when the image is cropped:
import {Cloudinary} from "@cloudinary/url-gen";
import {fill} from "@cloudinary/url-gen/actions/resize";
import {focusOn} from "@cloudinary/url-gen/qualifiers/gravity";
import {FocusOn} from "@cloudinary/url-gen/qualifiers/focusOn";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'family_bench'.
const myImage = cld.image('family_bench');
// Apply the transformation.
myImage.resize(fill().width(250).height(250).gravity(focusOn(FocusOn.faces())));
You can also use automatic gravity to determine what to keep in the crop automatically.
import {Cloudinary} from "@cloudinary/url-gen";
import {fill} from "@cloudinary/url-gen/actions/resize";
import {autoGravity} from "@cloudinary/url-gen/qualifiers/gravity";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'basketball_in_net'.
const myImage = cld.image('basketball_in_net');
// Apply the transformation.
myImage.resize(fill().width(200).height(300).gravity(autoGravity()));
For details on all resizing and cropping options, see resizing and cropping images.
Converting to another image format
You can deliver any image uploaded to Cloudinary in essentially any image format. There are three main ways to convert and deliver in another format:
- Specify the image's public ID with the desired extension.
- Explicitly set the desired format using the
format
action type of thedelivery
action. - Use
auto
format to instruct Cloudinary to deliver the image in the most optimized format for each browser that requests it.
For example:
1. To deliver a .jpg file in .gif format:
-
Either add the
.gif
extension to the public ID when instantiating theCloudinaryImage
:JSimport {Cloudinary} from "@cloudinary/url-gen" // Create and configure your Cloudinary instance. const cld = new Cloudinary({ cloud: { cloudName: 'demo' } }); // Use the image with public ID, 'docs/shoes', specifying the 'gif' extension. const myImage = cld.image('docs/shoes.gif'); // Return the delivery URL const myUrl = myImage.toURL();
This is the returned URL:
-
Or use the
delivery
action, settingformat
togif
(note thatmyImage.format('gif');
is an alias formyImage.delivery(format('gif'));
:JSimport {Cloudinary} from "@cloudinary/url-gen"; // Create and configure your Cloudinary instance. const cld = new Cloudinary({ cloud: { cloudName: 'demo' } }); // Use the image with public ID, 'docs/shoes'. const myImage = cld.image('docs/shoes'); // Set the format to GIF. myImage.format('gif'); // Return the delivery URL const myUrl = myImage.toURL();
This is the returned URL:
2. To let Cloudinary select the optimal format for each browser, set format
to auto
. For example, in Chrome, this image may deliver in .avif or .webp format (depending on your product environment setup):
import {Cloudinary} from "@cloudinary/url-gen";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'docs/shoes'.
const myImage = cld.image('docs/shoes');
// Request automatic format.
myImage.format('auto');
// Return the delivery URL
const myUrl = myImage.toURL();
This is the returned URL:
For more details, see:
- Delivering images in different formats
- Automatic format selection (f_auto)
- Tips and considerations for using f_auto
Applying image effects and filters
You can select from a large selection of image effects, enhancements, and filters to apply to your images. The available effects include a variety of color balance and level effects, tinting, blurring, pixelating, sharpening, automatic improvement effects, artistic filters, image and text overlays, distortion and shape changing effects, outlines, backgrounds, shadows, and more.
For example, the code below applies a cartoonify effect, rounding corners effect, and background color effect (and then scales the image down to a height of 300 pixels).
import {Cloudinary} from "@cloudinary/url-gen";
import {scale} from "@cloudinary/url-gen/actions/resize";
import {outline, cartoonify} from "@cloudinary/url-gen/actions/effect";
import {max} from "@cloudinary/url-gen/actions/roundCorners";
import {outer} from "@cloudinary/url-gen/qualifiers/outlineMode";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'actor'.
const myImage = cld.image('actor');
// Apply the transformation.
myImage
.effect(cartoonify())
.roundCorners(max())
.effect(outline().mode(outer()).width(100).color('lightblue'))
.backgroundColor('lightblue')
.resize(scale().height(300));
// Return the delivery URL
const myUrl = myImage.toURL();
For more details on the available image effects and filters, see Visual image effects and enhancements.
Adding text and image overlays
You can add images and text as overlays on your main image. You can apply the same types of transformations on your overlay images as you can with any image and you can use gravity settings or x and y coordinates to control the location of the overlays. You can also apply a variety of transformations on text, such as color, font, size, rotation, and more.
For example, the code below overlays a couple's photo on a mug image. The overlay photo is cropped using face detection with adjusted color saturation and a vignette effect applied. The word love is added in a pink, fancy font and rotated to fit the design. A balloon graphic is also added. Additionally, the final image is cropped and the corners are rounded.
import {Cloudinary} from "@cloudinary/url-gen";
import {Transformation} from "@cloudinary/url-gen";
import {scale, fill, crop} from "@cloudinary/url-gen/actions/resize";
import {source} from "@cloudinary/url-gen/actions/overlay";
import {byAngle} from "@cloudinary/url-gen/actions/rotate"
import {vignette} from "@cloudinary/url-gen/actions/effect";
import {byRadius, max} from "@cloudinary/url-gen/actions/roundCorners";
import {saturation, hue} from "@cloudinary/url-gen/actions/adjust";
import {Position} from "@cloudinary/url-gen/qualifiers/position";
import {compass} from "@cloudinary/url-gen/qualifiers/gravity";
import {image, text} from "@cloudinary/url-gen/qualifiers/source";
import {TextStyle} from "@cloudinary/url-gen/qualifiers/textStyle";
import {focusOn} from "@cloudinary/url-gen/qualifiers/gravity";
import {FocusOn} from "@cloudinary/url-gen/qualifiers/focusOn";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'coffee_cup'.
const myImage = cld.image('coffee_cup');
// Apply the transformation.
myImage
.resize(fill().height(250).width(400).gravity('south'))
.overlay(
source(
image('nice_couple')
.transformation(new Transformation()
.resize(crop().width(1.3).height(1.3).gravity(focusOn(FocusOn.faces())).regionRelative())
.adjust(saturation(50))
.effect(vignette())
.resize(scale().width(100))
.roundCorners(max())
)
)
.position(new Position().gravity(compass('center')).offsetX(-20).offsetY(20))
)
.overlay(
source(
image('balloon')
.transformation(new Transformation()
.resize(scale().height(55))
.adjust(hue(-20))
.rotate(byAngle(5))
)
)
.position(new Position().gravity(compass('center')).offsetX(30).offsetY(5))
)
.overlay(
source(
text('Love', new TextStyle('Cookie',40)
.fontWeight('bold'))
.textColor('#f08')
.transformation(new Transformation()
.rotate(byAngle(20)))
)
.position(new Position().gravity(compass('center')).offsetX(-45).offsetY(44))
)
.resize(crop().width(300).height(250).x(30))
.roundCorners(byRadius(60));
Image optimizations
By default, Cloudinary automatically performs certain optimizations on all transformed images. There are also a number of additional features that enable you to further optimize the images you use in your JavaScript application. These include optimizations to image quality, format, and size, among others.
For example, you can use the auto
qualifier for the fetch-format
and quality
attributes to automatically deliver the image in the format and quality that minimize file size while meeting the required quality level. Below, these two parameters are applied, resulting in a 50% file size reduction (1.4 MB vs. 784 KB) with no visible change in quality.
import {Cloudinary} from "@cloudinary/url-gen";
// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
cloud: {
cloudName: 'demo'
}
});
// Use the image with public ID, 'pond_reflect'.
const myImage = cld.image('pond_reflect');
// Request automatic format and quality.
myImage
.format('auto')
.quality('auto');
For an in-depth review of the many ways you can optimize your images, see Image optimization.