helion-prime
home about us blogs contacts

Easy image scaling for RoR developers

Published by alex.shapovalov on November 2, 2009 under ruby, web-development  

We have common task: image scaling [http://en.wikipedia.org/wiki/Image_scaling], and correct understanding that: we can’t ask users to provide image of appropriate sizes, just use width and height CSS parameters for images, and thumbnail is always required feature.

Luckily we have ImageMagic library [http://www.imagemagick.org] and program interfaces for popular languages.

install RMagic gem
# gem install rmagick

add small code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
require 'rubygems'
require 'RMagick'

class ImageController < ApplicationController

def index

  # determine basic params
  w = params[:w]
  h = params[:h]
  path = params[:path]

  if !w.to_s.empty? && !h.to_s.empty? && File.exists?(path)
      begin
        image = Magick::Image.read(path).first
        transformed_image = image.resize_to_fill(w.to_i, h.to_i)

        # send image
        send_data(transformed_image.to_blob, :disposition => 'inline',
         :type => "image/#{image.format.downcase}")

      rescue Exception => e
        Rails.logger.error e.message
        Rails.logger.error e.backtrace.join("\n")
        render :text => "Error processing image #{type}/#{aliaz}", :code => 404, :layout => false
      end

  end

end

Here to re-size images we use ‘resize_to_fill’ ImageMagic method:
re-size the image to fit within the specified dimensions while retaining the aspect ratio of the original image, and if necessary, crop the image in the larger dimension.

Sure you understand that resizing takes time and so you should cache re-sized images.

For additional info look thru:
[http://studio.imagemagick.org/RMagick/doc/]

Be Sociable, Share!

Leave a Reply

©2010 Helion-Prime Solutions Ltd.
Custom Software Development Agile Company.