Scaling images with RMagick

Posted by Dan Sosedoff on March 14, 2009

Simple class that providing scaling (rectangle and thumbnails) for images using RMagick and Ruby.
Code:

class ImageScale
    def change_geometry(sz,value)
        w = sz[0] ; h = sz[1]
            if w > h
                sz[0] = value
                sz[1] = ((value * h) / w).floor
            else
                sz[1] = value
                sz[0] = ((value * w) / h).floor
            end
            return sz
    end
 
    def make_rect(file_in,file_out, width, quality=85, sharp=false) 
        if FileTest.exists?(file_in)
            begin
                img = Magick::Image.read(file_in).first
                img.crop_resized!(width,width, Magick::CenterGravity)
                img = img.sharpen(0.5, 0.5) if sharp
                img.write(file_out) { self.quality = quality }
                return true if FileTest.exists?(file_out)
            rescue Magick::ImageMagickError
                return false
            end
        end
        return false
    end
 
    def make_thumb(file_in,file_out, width_to, quality=85, sharp=false) 
        if FileTest.exists?(file_in)
            begin
                img = Magick::Image.read(file_in).first
                info = [img.columns,img.rows]
                sz = change_geometry(info, width_to)
                img = img.resize(sz[0],sz[1])
                img = img.sharpen(0.5, 0.5) if sharp
                img.write(file_out) { self.quality = quality }
                return true if FileTest.exists?(file_out)
            rescue Magick::ImageMagickError
                return false
            end
        end
        return false
    end
end

Ok, let`s see how this class working. For example, we have source image:
Source Image

Function ImageScale.make_rect(src,dest,64) will produce such image:
Rectangle Image

Function ImageScale.make_thumb(src,dest,200) will produce thumbnail:
Thumbnail Image

There is optional parameter sharp to use sharping. Optional parameter quality is set to 85% compression value.

Trackbacks

Trackbacks are closed.

Comments

Comments are closed.