Quantcast
Channel: Good Sense » Sherman Lee
Viewing all articles
Browse latest Browse all 32

How I set up Cloudinary to replace Amazon S3 for image management

$
0
0

I was looking for an easy way to do image transformations and came across Cloudinary. It can crop, resize, detect faces, apply filters and a crap load of other stuff on the fly. Oh yeah, it’s a CDN too so you can say goodbye to storing/serving your images on Amazon S3.

Here’s an original uploaded photo to Cloudinary:

cloudinarycouple

Now with image transformation on the fly in the URL (thumb nail,  face detection, and cropping) http://a1.res.cloudinary.com/demo/image/upload/c_thumb,g_faces,h_114,w_114/couple.jpg

cloudinarycoupletransformed

Yep, that’s it. You no longer need to mess with ImageMagick or other libraries for you image processing needs! Try changing the height and width in the URL above.

Steps to get running in Rails for a nested model form

In this example, I’ll show you how I added image screenshots that belongs to a model called Project.

Add the following to your Gemfile and run bundle install:

gem 'carrierwave'
gem 'cloudinary'

Add a Cloudinary config file to config/cloudinary.yml.

Generate an uploader for CarrierWave  rails generate uploader Screenshot

A file should be generated at app/uploaders/screenshot_uploader.rb. I edited it to contain only:

class ScreenshotUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  process :convert => 'png'
  process :tags => ['project_screenshot']
end

The Screenshot model:

class Screenshot < ActiveRecord::Base
  attr_accessible :image, :image_cache, :project_id
  belongs_to :project
  mount_uploader :image, ScreenshotUploader
end

You can see our image attribute being mounted to the ScreenshotUploader  here. The image attribute is a string in the DB that references the location of the image on Cloudinary. The image_cache attribute is not stored in the DB but needs to be accessible for page reloads and validation errors while not losing the uploaded picture.

The Project model:

class Project < ActiveRecord::Base
  attr_accessible :name, :screenshots_attributes

  has_many :screenshots
  accepts_nested_attributes_for :screenshots
end

The screenshots_attributes and accepts_nested_attributes_for allows our forms in the view to handle multiple models in the same form.

The View for uploading the screenshot (in HAML)

= form_for @project do |f|
  = f.label :name
  = f.text_field :name
  = f.fields_for :screenshots do |screenshot_fields|
    = screenshot_fields.hidden_field :image_cache
    = screenshot_fields.file_field :image
  = f.submit "Add Project"

What do you use for image management?



Viewing all articles
Browse latest Browse all 32

Trending Articles