class FeaturedImage::Converter

Attributes

height[RW]
opts[RW]
width[RW]

Public Class Methods

convert(image, w, h, opts = {}) click to toggle source
# File lib/featuredimage/converter.rb, line 11
def self.convert(image, w, h, opts = {})
        converter = Converter.new(w, h, opts)
        converter.convert(image)
end
new(width, height, opts = {}) click to toggle source
# File lib/featuredimage/converter.rb, line 16
def initialize(width, height, opts = {})
        @width, @height = width, height

        # default convert options
        @opts = {
                :format => "JPG",
                :quality => 60
        }
        @opts.merge!(opts)
end

Public Instance Methods

convert(image) click to toggle source
# File lib/featuredimage/converter.rb, line 27
def convert(image)
        target_size = {w:@width, h:@height}
        original_size = {w:image.columns, h:image.rows}

        resized_size = get_resized_size(original_size, target_size)
        resized_image = image.resize(resized_size[:w], resized_size[:h])

        offset = get_offset(target_size, resized_size)
        cropped_image = resized_image.crop(offset[:x], offset[:y], target_size[:w], target_size[:h])

        image_to_blob(cropped_image)
end

Private Instance Methods

get_offset(target_size, resized_size) click to toggle source
# File lib/featuredimage/converter.rb, line 53
def get_offset(target_size, resized_size)
        offset_x = (resized_size[:w] - target_size[:w]) / 2
        offset_y = (resized_size[:h] - target_size[:h]) / 2
        {:x => offset_x, :y => offset_y}
end
get_resized_size(src, dst) click to toggle source
# File lib/featuredimage/converter.rb, line 41
def get_resized_size(src, dst)
        w_ratio = dst[:w].to_f / src[:w]
        h_ratio = dst[:h].to_f / src[:h]
        ratio = 0
        if w_ratio > h_ratio
                ratio = w_ratio
        else
                ratio = h_ratio
        end
        {w:(src[:w] * ratio).to_i, h:(src[:h] * ratio).to_i}
end
image_to_blob(image) click to toggle source
# File lib/featuredimage/converter.rb, line 59
def image_to_blob(image)
        opts = @opts
        image.to_blob{
                opts.each{|k, v|
                        self.send(k.to_s + '=', v)
                }
        }
end