Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

ActsAsImage

API docs

ActsAsImage is a Rails plug-in that scales images and saves them to disk. It uses RMagick, so it can handle all the image formats ImageMagick can. Images are saved as either JPEG or GIF, depending on if it’s an animation or not.

I’ve intentionally kept it very simple. If you want something a bit more feature-rich, other plug-ins such as Rick Olson’s attachment_fu are probably more to your liking.

Installing

Download the plugin from Github and put it in the vendor/plugins directory.

Model

If you haven’t got a model to represent your images yet, ActsAsImage can generate one for you, along with the necessary migration, that’s set up to use the plug-in.

script/generate acts_as_image model Image
rake db:migrate

If you want to use an existing model, make sure the database table has the fields content_type, hash_string and original_filename.

The model will look something like this:

class Image < ActiveRecord::Base

  acts_as_image #Must come first

  self.image_sizes = {
    :original => '100%x100%',
    :large => '>800x600',
    :medium => '>640x480',
    :small => '>320x200',
    :thumb => ['100x100!', :crop]
  }

  self.image_save_path = File.join(RAILS_ROOT, 'public', 'images', 'uploads')
  self.image_read_path = ['images', 'uploads'].join('/')

end

Image.image_sizes contains a hash with the names and sizes of the images that will be written to disk. The key will be used as the filename, and the value is an RMagick geometry string.

Using it

To save images with this model, you attach the uploaded file to the model’s virtual file attribute:

class PicturesController

  def create
    image = Image.new
    image.file = params[:image][:file]
    image.save
  end

end

You can now access the image’s URL via the url method:

<%= image_tag(image.url('small'), :alt => h(image.title)) %>

Other stuff

To keep this page uncluttered, more information on how to customise how the plug-in works has been moved into sub-pages of this page (links at the top).

Comments

82 comments

I am Citizen Insane