Cloudinary Blog

Ruby on Rails and Cloudinary - image management for an amazing web-dev framework

End to end image management solution for Ruby on Rails

Rails is a great web development framework that was recently considered the coolest framework around. While other frameworks have gained popularity over time, Rails remains one of the most popular web development frameworks to date..

Cloudinary's Rails community includes active Ruby on Rails developers who use Cloudinary’s APIs to streamline and manage their image lifecycle on their sites and web applications. In fact, approximately 33% of Cloudinary’s paying customers use Ruby on Rails. Therefore, we are pleased to be a part of this year's RailsConf in Atlanta, presenting how simple it is to handle image uploads, manipulation and delivery in Rails applications with Cloudinary.

Image management with Ruby on Rails

The concept of Ruby on Rails stemmed from the preference of convention over configuration in terms of common development tasks. This way, you can write code specifically for your core business logic rather than spending time writing common code found in every web application.

The missing link in this revolutionary approach to code writing was image management. Various GEMs attempted to solve this image management challenge in various ways, such as managing attachment and upload flows, or creating packages that wrapped image processing and applications.

Quite a lot of code is needed to make the image management flow truly work while maintaining your online site. This includes code to manage user uploaded media files of all sizes, safely storing them online, dynamically manipulating them to match your website, web application or mobile app's graphic design, browser type and device resolution, then delivering them optimized, as fast as possible, to enhance user experience.  

Ruby on Rails has been our personal favorite framework since version 1.0. Therefore, it is no surprise that Cloudinary has provided a Ruby GEM from day one of our service to simplify the lives of web developers who use Ruby on Rails. By simply adding one-liners to your code, you can integrate Cloudinary's cloud-based solution with your Rails code. This essentially eliminates the R&D work involved in image management, ultimately reducing related maintenance and IT costs. This Ruby GEM has been used by thousands of customers across the globe, letting them enjoy the most feature-rich image manipulation capabilities.

End to end image management for RoR developers

Upload to the cloud

Upload can be done from your server-side code or by letting your users upload directly from their browsers using a jQuery plugin. You can upload images and any other files from your Ruby code or Ruby on Rails server. To simplify the upload process and support rich client-side applications, your images can be uploaded directly from a browser to the cloud with no predefined authentication using our direct unsigned upload.

Uploading is done over HTTPS using a secure protocol based on the credentials of your Cloudinary account.

The following simple Ruby command uploads a local file to Cloudinary from your server-side Rails code:

Cloudinary::Uploader.upload('/home/my_image.jpg')

Each image uploaded to Cloudinary is assigned a unique Public ID and is available for immediate delivery and transformation. Learn more.

Below is an example of Rails' view method that adds a file input field to your HTML page that performs upload to the cloud directly from your user’s browser:

<%= cl_image_upload_tag(:image_id, :crop => :limit, :width => 1000, :height => 1000) %>

View helper methods to manipulate and embed images

These are used to embed images that were previously uploaded to the cloud, manipulate them on-the-fly to match your graphic design, apply effects and any type of crop you wish, then quickly deliver them optimized via CDN to your users. View helper methods create HTML image tags so that an image's URL includes dynamic manipulation parameters, which are part of Cloudinary's rich set of image manipulation capabilities.

Images are implicitly and automatically optimized to a smaller file size while maintaining high visual quality. Cloudinary also supports dynamic browser detection to deliver modern file formats, resolution, pixel density for retina display and responsive layout design to further optimize and simplify development.  

For example, an image was uploaded to Cloudinary with the public ID of bike. The following method generates an HTML image tag of the uploaded image (scaled down):

cl_image_tag("bike.jpg")

Original uploaded image

The code example below is of a cloud-based manipulation result of the same image. The image is cropped using automatic face detection to a circular thumbnail of 200 pixels.

cl_image_tag("bike.jpg", :radius=>"max", :width=>200, :height=>200, :crop=>:thumb, :gravity=>:face)

Face detection based circular cropped image

The cl_image_tag view helper method generates an HTML image tag with a dynamic image URL as the source attribute. The image is delivered optimized via a fast CDN using an on-the-fly manipulation URL:

Ruby:
cl_image_tag("bike.jpg", :width=>200, :height=>200, :gravity=>"face", :radius=>"max", :crop=>"thumb")

The following example shows a more advanced manipulation of the same uploaded image. This time generating an image of 400x400 pixels using face detection based cropping. Color saturation is increased by 100%, a watermark is added, as well as a dynamic text overlay. A vignette effect is applied and the image is deliver to support Retina displays with DPR (Device Pixel Ratio) of 2.0.

cl_image_tag("bike.jpg", :transformation=>[
  {:width=>400, :height=>400, :crop=>:fill, :gravity=>:face, :effect=>"saturation:100"},
  {:opacity=>50, :overlay=>"cloudinary_icon", :width=>0.5, :flags=>:relative, :effect=>"brightness:200"},
  {:opacity=>90, :color=>"white", :overlay=>"text:Montserrat_38_bold:RailsConf%202015", :y=>180, :gravity=>:south},
  {:effect=>"vignette:100"},
  {:dpr=>2.0}
  ])

Advanced cloud-based image manipulation integrated with a Rails view

Learn more about Cloudinary’s Rails image manipulation.

CarrierWave plugin

CarrierWave is a popular Ruby GEM that is used to manage the file attachment and upload process, in general. It integrates all Model View Controller (MVC) aspects of upload and attachment management. Cloudinary provides a plugin for CarrierWave that makes the switch from existing storage (e.g., S3) and from local image processing (e.g., using RMagick or MiniMagick), to Cloudinary's cloud-based image manipulation service. Delivery is seamless via CDN, and simply requires you to change a single line of code in your model using CarrierWave.

Below is a sample code of a CarrierWave uploader class definition with Cloudinary’s plugin:

class PictureUploader < CarrierWave::Uploader::Base

  include Cloudinary::CarrierWave

  process :convert => 'png'
  process :tags => ['post_picture']
  
  version :standard do
    process :resize_to_fill => [100, 150, :north]
  end
  
  version :thumbnail do
    resize_to_fit(50, 50)
  end

end

By the way, Attachinary is another great attachment management plugin that uses Cloudinary internally.

See our documentation of Ruby On Rails integration for more details.

And much more...

At Cloudinary, we provide image management features that are available via our Ruby GEM. For example, we utilize a Rake task to sync your static website images to the cloud to perform both fast delivery via CDN and manipulation. We also provide a tool to manage the process of migrating existing images to the cloud and we provide an administrative API that allows you to perform housekeeping tasks, keeping your images organized (e.g., browsing, tagging, deleting).

There are plenty more features that we provide, all of which include add-ons for image processing, moderation, manipulation, optimization, and are wrapped by our Ruby GEM, so they are packaged in the simplest way for developers to use.

Ruby on Rails will soon be coming out with its fifth major version, showing that the popular web development platform is continuing to evolve and face new challenges with components such as the new Action Cable, Rails for API-only apps and more. Nevertheless, since Cloudinary takes care of your entire image management pipeline, as Rails developers, there's no reason you should take on this task on your own. In addition, Cloudinary provides integration with client-side frameworks, such as jQuery and AngularJS, that you can use to further simplify integration with your web application’s UI layer. With Cloudinary's Ruby GEM, image management can be done in the cloud without the need to install local software or deal with complex upload flows. Check out our Ruby documentation and feel free to try it out for yourself.

Rails fan? If you don't have a Cloudinary account yet, sign up for a free account here.

Recent Blog Posts

Hipcamp Optimizes Images and Improves Page Load Times With Cloudinary

When creating a website that allows campers to discover great destinations, Hipcamp put a strong emphasis on featuring high-quality images that showcased the list of beautiful locations, regardless of whether users accessed the site on a desktop, tablet, or phone. Since 2015, Hipcamp has relied on Cloudinary’s image management solution to automate cropping and image optimization, enabling instant public delivery of photos, automatic tagging based on content recognition, and faster loading of webpages. In addition, Hipcamp was able to maintain the high standards it holds for the look and feel of its website.

Read more
New Image File Format: FUIF: Why Do We Need a New Image Format

In my last post, I introduced FUIF, a new, free, and universal image format I’ve created. In this post and other follow-up pieces, I will explain the why, what, and how of FUIF.

Even though JPEG is still the most widely-used image file format on the web, it has limitations, especially the subset of the format that has been implemented in browsers and that has, therefore, become the de facto standard. Because JPEG has a relatively verbose header, it cannot be used (at least not as is) for low-quality image placeholders (LQIP), for which you need a budget of a few hundred bytes. JPEG cannot encode alpha channels (transparency); it is restricted to 8 bits per channel; and its entropy coding is no longer state of the art. Also, JPEG is not fully “responsive by design.” There is no easy way to find a file’s truncation offsets and it is limited to a 1:8 downscale (the DC coefficients). If you want to use the same file for an 8K UHD display (7,680 pixels wide) and for a smart watch (320 pixels wide), 1:8 is not enough. And finally, JPEG does not work well with nonphotographic images and cannot do fully lossless compression.

Read more
 New Image File Format: FUIF:Lossy, Lossless, and Free

I've been working to create a new image format, which I'm calling FUIF, or Free Universal Image Format. That’s a rather pretentious name, I know. But I couldn’t call it the Free Lossy Image Format (FLIF) because that acronym is not available any more (see below) and FUIF can do lossless, too, so it wouldn’t be accurate either.

Read more
Optimizing Video Streaming and Delivery: Q&A with Doug Sillars

Doug Sillars, a digital nomad and a freelance mobile-performance expert, answers questions about video streaming and delivery, website optimization, and more.

Doug Sillars, a freelance mobile-performance expert and developer advocate, is a Google Developer Expert and the author of O’Reilly’s High Performance Android Apps. Given his extensive travels across the globe—from the UK to Siberia—with his wife, kids, and 11-year-old dog, Max, he has been referred to as a “digital nomad.” So far in 2018, Doug has spoken at more than 75 meetups and conferences!

Read more