Cloudinary Blog

Advanced image transformations in the cloud with CarrierWave & Cloudinary

by Nadav Soferman
In a previous post we've shown how you can easily manage your Ruby on Rails image uploads with CarrierWave and Cloudinary. Many of our Rails readers found this very useful, as it depicted a powerful image management solution that is trivial to integrate - use the popular CarrierWave GEM together with the Cloudinary GEM, add a single 'include' line to your code and that's it. All your images are automatically uploaded to the cloud and delivered through a fast CDN. Better yet, all image transformations defined in your CarrierWave uploader class are generated in the cloud by Cloudinary. No need to install and setup any image processing library (goodbye RMagick, ImageMagick, GraphicsMagick, MiniMagick, etc.). You also don't need to worry any more about CPU power, storage space, image syncing between multiple servers, backup and scale.
 
In this post, we wanted to show how you can use all of Cloudinary's additional cool image management and manipulation features together with CarrierWave - apply effects and filters, face detection based cropping, JPG quality modification, adding watermarks and more.
 

Custom and dynamic transformations 

Cloudinary's plugin for CarrierWave supports all of CarrierWave's standard resize and cropping capabilities. In addition, you can apply any custom transformation supported by Cloudinary by using the cloudinary_transformation method. You can call cloudinary_transformation in conjunction with the standard resize and crop methods. 
 
The following uploader class shows a common usage example with custom transformations:
class PictureUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  # Generate a 164x164 JPG of 80% quality 
  version :simple do
    process :resize_to_fill => [164, 164, :fill]
    process :convert => 'jpg'
    cloudinary_transformation :quality => 80
  end

  # Generate a 100x150 face-detection based thumbnail,
  # round corners with a 20-pixel radius and increase brightness by 30%.
  version :bright_face do
    cloudinary_transformation :effect => "brightness:30", :radius => 20,
        :width => 100, :height => 150, :crop => :thumb, :gravity => :face
  end

end
 

Chained Transformations 

You can take this further by applying chained transformations. Any set of transformations can be applied as an incoming transformation while uploading or as part of the different versions that are generated lazily or eagerly during upload. 
 
The following uploader class includes chained transformations applied using the transformation parameter of the cloudinary_transformation method.
class PictureUploader < CarrierWave::Uploader::Base      
  include Cloudinary::CarrierWave
 
  # Apply an incoming chained transformation: limit image to 1000x1200 and 
  # add a 30-pixel watermark 5 pixels from the south east corner.   
  cloudinary_transformation :transformation => [
      {:width => 1000, :height => 1200, :crop => :limit}, 
      {:overlay => "my_watermark", :width => 30, :gravity => :south_east, 
       :x => 5, :y => 5}
    ]        
  
  # Eagerly transform image to 150x200 with a sepia effect applied and then
  # rotate the resulting image by 10 degrees. 
  version :rotated do
    eager
    cloudinary_transformation :transformation => [
        {:width => 150, :height => 200, :crop => :fill, :effect => "sepia"}, 
        {:angle => 10}
      ]
  end
end
Some websites have a graphic design that forces them to display the same images in many different dimensions. Formally defining multiple uploader's versions might become cumbersome. In this case, you can still utilize CarrierWave while leveraging Cloudinary's dynamic transformations by applying any desired transformation while building your view. 
 
Any version can be generated dynamically from your view without depending on CarrierWave versions. Simply use the full_public_id attribute with cl_image_tag to build cloud-based transformation URLs for the uploaded images attached to your model.
cl_image_tag(post.picture.full_public_id, :format => "jpg", 
             :width => 100, :height => 200:crop => :crop, 
             :x => 20, :y => 30, :radius => 10)


Custom coordinates based cropping

If you allow your users to manually select their images cropping areas, we recommend you keep these crop coordinates persistently in your model. This way you'll be able to crop the original images differently in the future. 
 
The following uploader class fetches the custom coordinates from attributes of the model object. The custom_crop method in this example simply returns a Hash of additional Cloudinary transformation parameters to apply.
class PictureUploader < CarrierWave::Uploader::Base  
  include Cloudinary::CarrierWave  
 
  version :full do    
    process :convert => 'jpg'
    process :custom_crop
  end    
  
  def custom_crop      
    return :x => model.crop_x, :y => model.crop_y, 
      :width => model.crop_width, :height => model.crop_height, :crop => :crop      
  end
end
If you want to store only the cropped version of the image, you can use the incoming transformation of Cloudinary's upload API. This way only the cropped image is stored in the cloud. You can then use additional transformations to resize the cropped image. 
 
The following example calls process :custom_crop in the class itself, instead of in a 'version', while the custom-coordinates are kept as transient attributes on the model (defined with attr) instead of storing them persistently.
class PictureUploader < CarrierWave::Uploader::Base  
  include Cloudinary::CarrierWave  
 
  process :custom_crop
 
  version :thumbnail do    
    process :convert => 'jpg'
    resize_to_fill(120, 150, 'North')
  end    
  
  def custom_crop      
    return :x => model.crop_x, :y => model.crop_y, 
      :width => model.crop_width, :height => model.crop_height, :crop => :crop      
  end
end


Private images and eager transformations 

Cloudinary supports uploading private images to the cloud. These images won't be accessible to your users. See our blog post for more details. Together with the Strict Transformations feature, you can specify that only certain transformations (e.g., low resolution thumbnails, watermarked images) are available for your users.
 
For uploading images as private, simply add 'make_private' to your uploader class. This will also make all generated delivery URLs to access the private images correctly. 
 
The versions you define in your uploader class should use only named or dynamic transformations marked as Allowed. Alternatively, you can tell Cloudinary to eagerly generate all transformed versions while uploading. This way you can keep all your transformations as strict (disallowed).
 
The following uploader class shows how to use private images and eager transformations:
class PictureUploader < CarrierWave::Uploader::Base      
  include Cloudinary::CarrierWave
  make_private
  
  # Generate a 164x164 JPG of 80% quality 
  version :simple do
    process :resize_to_fill => [164, 164, :fill]
    process :convert => 'jpg'
    cloudinary_transformation :quality => 80
    eager
  end
  
  version :thumbnail do
    resize_to_fit(50, 50)
    eager
  end
 
end


Summary

If you are a Ruby on Rails developer, you should definitely consider using CarrierWave (if you haven't done so already). Together with Cloudinary you can reach a powerful image management, manipulation and delivery solution with almost zero efforts and code changes.
 
If you're looking for a CarrierWave alternative, make sure you check out the brand new Attachinary Ruby GEM. Attachinary provides a modern image attachment solution to your Rails application while employing Cloudinary for cloud-based storage, image transformations and delivery. Read more about it here.
 
We've mentioned 'Ruby on Rails' quite a lot, though both CarrierWave and the Cloudinary plugin support a standard ActiveRecord model as well as a Mongoid model. In addition, some of our customers use this solution for their non-Rails frameworks, such as Sinatra.
 
For more details, see our documentation.
 
If you have additional thoughts on how we can make your life easier when managing images and attachments in your Rails applications, make sure you tell us about them. If you don't have a Cloudinary account already, you can sign up for a free account in seconds.

Recent Blog Posts

Optimizing web performance and your bottom line

by Robert Moseley
Optimize your website and app for maximum user engagement
Patience is not a virtue for website visitors and online shoppers. Every fraction of a second counts when it comes to keeping – or losing – a visitor to your website.  
 
Loading time is a major contributing factor to page abandonment, according to an infographic on the Kissmetrics blog using statistics from Akamai and Gomez. Because the average web visitor has no patience for a page that takes too long to load, abandonment increases as a percentage with every second of load time. Nearly 40 percent of users will abandon a page after 10 seconds, the blog noted. Mobile Internet users probably experience the most frustration with this issue –  73 percent noted that they’ve encountered a website that was too slow to load. 
Read more
Is your website offering the best user experience?
 
The most common frustrations voiced by people when visiting a website are the time it takes for pages to load and the amount of bandwidth some sites eat from their monthly mobile plans. 
 
What these users might not realize is that, in many cases, the culprit is the same: website image performance. Ensuring images are optimized is particularly important to businesses who manage these sites since they account for the majority of the downloaded bytes on a web page, and can slow down load times considerably. 
Read more
Improve your site with content personalization & A/B testing

Personalization of web content is becoming increasingly important for businesses to gain – and maintain – their competitive advantage. Web personalization is key to increasing conversion rates and return rates, as well as boosting retention, time-on-site, and page views, according to a December 2015 VentureBeat study, which noted that 87 percent of companies have seen a lift of at least 5 percent in their most important metrics as a result of personalization. 
Read more
Dynamic ZIP files generation with a single line of code

As a developer, you want to allow your users to download multiple files in a single click. An easy way to download multiple files and share them is to generate a ZIP file. When images are involved, you may also want to normalize the original images before including them in the ZIP file, by scaling them down to the same maximum resolution or converting them to the same format.

Read more