Rails image transformations

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 manipulate your assets using a set of transformation parameters. All manipulations 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.

Cloudinary's Rails library simplifies the generation of transformation URLs for easy embedding of assets in your Rails application.

See also: Rails video manipulation

Deliver and transform images

You can deliver your images using methods that generate image tags or via direct URL-building directives.

The cl_image_tag method

You can add images to your Rails view using Cloudinary's cl_image_tag helper method, instead of the standard Rails 'image_tag' method. This method generates the full image resource URL based on the given transformation parameters and then internally uses 'image_tag' to add the image tag to your HTML code:

Copy to clipboard

The code above generates the following HTML image tag:

Copy to clipboard
<img src="https://res.cloudinary.com/demo/image/upload/sample">

You can also include transformation parameters in the request, for example, to deliver a JPEG image padded to a width of 400 pixels:

Copy to clipboard
cl_image_tag("sample.jpg", :width => 400, :crop => "pad")

You can either add transformations directly to your cl_image_tag method (all transformations will be in a single, flat component of the resulting URL source, as above), or you can define them with the transformation parameter.

Copy to clipboard
cl_image_tag("sample.jpg", :transformation => { :width => 400, :crop => "pad" })

Additionally, you can add other, non-transformation parameters to the cl_image_tag such as the asset version, configuration parameters and HTML5 image tag attributes.

For example:

Copy to clipboard
cl_image_tag("docs/casual", :version=>"1573726751", :cloud_name=>"demo", :secure=>"true", :alt=>"Casual Jacket", :width=>500, :height=>500, :crop=>"fill")

is compiled by Rails to:

Copy to clipboard
<img src="https://res.cloudinary.com/demo/image/upload/c_fill,h_500,w_500/v1573726751/docs/casual" alt="Casual Jacket">

Chaining transformations

Cloudinary supports powerful transformations. You can even combine multiple transformations together as part of a single transformation request, e.g. crop an image and add a border. In certain cases you may want to perform additional transformations on the result of the previous transformation request. To do that, you can use chained transformations.

To apply chained transformations in a transformation URL, you include multiple transformation components separated by '/'. Each transformation component is applied to the result of the previous one. In Ruby, applying multiple transformations is done by specifying the transformation parameter as an array of transformation hashes. The following example first crops the original image to a specific set of custom coordinates and then transforms the result so it fills a 130x100 rectangle:

Copy to clipboard
cl_image_tag("brown_sheep.jpg", :transformation=>[
  {:x=>355, :y=>410, :width=>300, :height=>200, :crop=>"crop"},
  {:width=>130, :height=>100, :crop=>"fill"}
Simple chaining example

The following example applies 4 chained transformations: custom cropping to 300x200, fill to 130x100, rotate by 20 degrees and then scale to 50%:

Copy to clipboard
cl_image_tag("brown_sheep.jpg", :transformation=>[
  {:x=>355, :y=>410, :width=>300, :height=>200, :crop=>"crop"},
  {:width=>130, :height=>100, :crop=>"fill"},
  {:width=>0.5, :crop=>"scale"}
More complex chaining example

For more information on image transformations, see Apply common image transformations.

Direct URL building

The cl_image_tag method described above generates an HTML image tag. In certain conditions, you might want to generate a transformation URL directly, without the containing image tag. To return only the URL, either use the cl_image_path or cloudinary_url view helper methods, or use the Ruby command: Cloudinary::Utils.cloudinary_url. Here are few examples:

Copy to clipboard
<%= cl_image_path("sample.jpg", :width => 100, :height => 150, :crop => :fill) %>      
<%# Output: "https://res.cloudinary.com/demo/image/upload/c_fill,h_150,w_100/sample.jpg" %>
Copy to clipboard
<%= cloudinary_url("sample_spreadsheet.xls", :resource_type => :raw) %>
<%# Output: "https://res.cloudinary.com/demo/raw/upload/sample_spreadsheet.xls" %>
Copy to clipboard
Cloudinary::Utils.cloudinary_url("sample.jpg", :width => 100, :height => 150, :crop => :fill)
=> "https://res.cloudinary.com/demo/image/upload/c_fill,h_150,w_100/sample.jpg"

Enhanced image_tag

Most examples shown here are based on using Cloudinary's cl_image_tag to embed and transform images. You can alternatively use the standard Rails 'image_tag' to get the same functionality by setting enhance_image_tag to true in your global configuration parameters.

After setting the configuration parameter, you can use the standard Rails image_tag method to embed any uploaded images or transformed images, as long as you also include the type parameter (generally set to 'upload', but for more details see the Access control documentation).

For example:

Copy to clipboard
<%= image_tag("sample.jpg", :type => :upload, 
    :width => 100, :height => 150, :crop => :fill) %>

<%# Output: <img width="100" height="150" 
    src="https://res.cloudinary.com/demo/image/upload/c_fill,h_150,w_100/sample.jpg" /> %>

The same approach can be used to embed a remotely fetched and transformed image through Cloudinary:

Copy to clipboard
<%= image_tag("https://example.com/logo.png", :type => "fetch") %>

<%# Output: <img src="https://res.cloudinary.com/demo/image/fetch/https://example.com/logo.png" /> %>

Static files

While Cloudinary's service focuses on user-uploaded images, you can use Cloudinary to manage the static files you have in your web application as well, such as background images, buttons, icons, scripts, stylesheets. These too can be delivered through a CDN, offloading their delivery from your servers and improving your website's performance.

Cloudinary's Ruby gem simplifies and streamlines the process of uploading your static files to the cloud and delivering them through a CDN.

To upload all your Ruby-on-Rails applications' static files to Cloudinary, run the following Rake command:

Copy to clipboard
rake cloudinary:sync_static

This Rake task finds all the files in all common public folders and in Rails Asset Pipeline’s image asset folders. Afterwards, it uploads all new and modified files to Cloudinary. Uploaded files and their versions are maintained using a local .cloudinary.static file. Make sure you commit this file to your source control.

After uploading your static files to Cloudinary, edit your cloudinary.yml file and set the following configuration parameters to 'true':

Copy to clipboard
enhance_image_tag: true
static_file_support: true

Every image_tag call in your views will now automatically check if the image was uploaded to the cloud (using .cloudinary.static) and if so, will generate a remote Cloudinary CDN URL. For example:

Copy to clipboard
<%= image_tag(“logo.png”, :width => 100, :height => “100”) %>

Will now generate the following HTML code:

Copy to clipboard
<img src=https://res.cloudinary.com/demo/image/asset/
      logo-5740ed843b23d0b86e48081f43a45b9c width=100 height=100/>

The Ruby gem automatically delivers background images defined in your CSS, SCSS or SASS files using the default image-url directly or Cloudinary's cloudinary-url custom directive.

Apply common image transformations

This section provides an overview and examples of the following commonly used image transformation features, along with links to more detailed documentation on these features:

Keep in mind that this section is only intended to introduce you to the basics of using image transformations with Ruby and Rails.

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 Image transformation 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:

Copy to clipboard
cl_image_tag("family_bench.jpg", :width=>250, :height=>250, :gravity=>"faces", :crop=>"fill")

Original image before face recognition cropping Original image Fill cropping with 'faces' gravity Fill cropping with 'faces' gravity

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:

  • Specifying the image's public ID with the desired extension.
  • Explicitly set the desired format using the fetch_format parameter.
  • Use the auto fetch_format to instruct Cloudinary to deliver the image in the most optimized format for each browser that requests it.

For example:

Deliver a .jpg file in .gif format:

Copy to clipboard

Let Cloudinary select the optimal format for each browser. For example, in Chrome, this image delivers in .webp format.

Copy to clipboard
cl_image_tag("cloud_castle.jpg", :width=>350, :fetch_format=>:auto, :crop=>"scale")

For more details see Image format support.

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).

Copy to clipboard
cl_image_tag("actor.jpg", :transformation=>[
  {:effect=>"outline:100", :color=>"lightblue"},
  {:height=>300, :crop=>"scale"}
An image with several transformation effects

For more details on the available image effects and filters, see Applying image effects and filters.

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.

Copy to clipboard
cl_image_tag("coffee_cup.jpg", :transformation=>[
  {:width=>400, :height=>250, :gravity=>"south", :crop=>"fill"},
  {:overlay=>"nice_couple", :width=>1.3, :height=>1.3, :gravity=>"faces", :flags=>"region_relative", :crop=>"crop"},
  {:flags=>"layer_apply", :width=>100, :radius=>"max", :gravity=>"center", :y=>20, :x=>-20, :crop=>"scale"},
  {:overlay=>"balloon", :height=>55},
  {:effect=>"hue:-20", :angle=>5},
  {:flags=>"layer_apply", :x=>30, :y=>5},
  {:overlay=>{:font_family=>"Cookie", :font_size=>40, :font_weight=>"bold", :text=>"Love"}, :effect=>"colorize", :color=>"#f08"},
  {:angle=>20, :flags=>"layer_apply", :x=>-45, :y=>44},
  {:width=>300, :height=>250, :x=>30, :crop=>"crop"},
An image with many transformations and overlays applied

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 application. These include optimizations to image quality, format, and size, among others.

For example, you can use the auto value 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.

Copy to clipboard
cl_image_tag("pond_reflect.jpg", :quality=>"auto", :fetch_format=>:auto)
50% file size optimization using auto format and auto quality features

For an in-depth review of the many ways you can optimize your images, see Image optimization.

Responsive image settings

Responsive web design is a method of designing websites to provide an optimal viewing experience to users, irrespective of the device, window size, orientation, or resolution used to view it. Ensuring that optimal experience means you should avoid sending high resolution images that get resized client-side, with significant bandwidth waste for users of small displays. Instead, you should always deliver the right size image for each device and screen size.

For example, you can ensure that each user receives images at the size and device pixel ratio (dpr) that fit their device using the auto value for the dpr and width attributes. The auto value is replaced with actual values on the client side based on the actual browser settings and window width:

Copy to clipboard
cl_image_tag("myphoto", :transformation => 
    { :dpr => "auto", :responsive => true, :width => "auto", :crop => "scale", :angle => 20}, 
    { :effect => "art:hokusai", :border => "3px_solid_rgb:00390b", :radius => 20}

Cloudinary offers several options for simplifying the complexity of delivering responsive images. For a detailed guide on how to implement these options, see Responsive images.

✔️ Feedback sent!