Rails: Custom image sizes using has_attachment

Ever wanted to offer users the possibility to define their very own image sizes for uploaded pictures?

Here’s how you can quickly do that.

You will have a class acting as a an attachment such as:

class AssetImage < ActiveRecord::Base

has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 1.megabytes,
:path_prefix => "public/system/images/#{ActiveRecord::Base.configurations[RAILS_ENV]['domain_name']}/assets/images",
:thumbnails => { :large => '450>', :normal => '300', :medium => '200', :thumbnail => [100,75] },
:processor => :rmagick

validates_as_attachment

...

First add a cattr_accessor to store your custom size in the class:

cattr_accessor :custom_size

Now, add a before_save callback which takes the assigned value and adds it to the list of requested image sizes. It is using the value as a minimum size while keeping aspect ratio.

#store custom size
def before_save
  return if AssetImage.custom_size.nil?
  attachment_options[:thumbnails][:custom] = AssetImage.custom_size.to_s + ">"
end

In your controller do something like this: Take a value from your parameters and store it in your model to have your image customized.

def add_image
  AssetImage.custom_size = params[:custom_size].to_i.to_s rescue "100"
  a = AssetImage.new(params[:asset_image])
  a.save
  redirect_to :action => :index
end

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.