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.
blog comments powered by Disqus

Recent Blog Posts

Control the zoom level with automatic image cropping

Many websites now offer their users the ability to upload images and profile pictures, making it a challenge for web designers to maintain a certain graphic design and style when subsequently displaying these images. The profile pictures may need to be smartly cropped to focus on the faces, with some sites that prefer close-ups of faces and others that prefer including more background when displaying images of people.

Read more
Introducing cloud based service for video management

They say that a picture is worth a thousand words. For modern websites, a video surely takes the visual impact to a whole new level.

Nowadays, people enjoy the amazing capability of shooting videos with smartphone cameras that easily fit in their back pockets and are accessible nearly everywhere. Modern web applications have an opportunity to dramatically increase their visual impact by showcasing these videos online. Between news reports, user shared video snippets, explainer videos and ad campaigns, we see more and more videos appearing daily in our visited websites.

Read more
Automatic and accurate red eye removal with Cloudinary

Red eye often happens due to the use of flash in low light conditions as the light hits the eye very quickly and into the retina. It then bounces off of the back of the eye and emits a red color due to the blood vessels there. Although more professional modern cameras and flashes generally prevent this from happening, red eye may still occur with simpler, smaller cameras (including smartphones). There are various software solutions for red eye removal available on mobile devices and desktops, some of which require manual processing to get good results.

Read more
How to detect and prevent malware infected user uploads

Social networking sites allow users to upload images or other types of files that are immediately available to other users via news feeds or notifications. In some cases, attackers can directly spread infected files, but more commonly, they leverage the viral effect and the fact that users are simply unaware that their files are infected through sharing and collaborating with others. As a site owner or application developer, it is your responsibility to protect users and prevent these situations from occurring. Fortunately, Cloudinary makes this easier with its Metascan add-on.

Read more