ruby on rails - RMagick changing image extents with gravity -


i've got image i'd 'pad' white space , centre.

in cases need resize image 16 or 32 pixels 32 pixels. if image 16 pixels, want add 8px of white space on each side, making 32 pixel image (with original floating in middle).

if it's 32 pixel image, nothing changes.

i'm using rmagick conversion:

image.change_geometry!("#{size}x#{size}") { |cols, rows, img|   newimg = img.extent(cols, rows)   newimg.write("#{rails_root}#{path}/#{name}.png") } 

which working ok, smaller images in top left of new image, not centred. looking @ gravity setting, seems need, can't work out how specify in call?

thanks in advance.

check implementation of following carrierwave function http://rubydoc.info/gems/carrierwave/0.5.1/carrierwave/rmagick#resize_and_pad-instance_method

this version of above method using rmagick dependency

require 'rmagick' include magick  module converter   def self.resize_and_pad(img, new_img_path, width, height, background=:transparent, gravity=::magick::centergravity)     img.resize_to_fit!(width, height)     new_img = ::magick::image.new(width, height)     if background == :transparent       filled = new_img.matte_floodfill(1, 1)     else       filled = new_img.color_floodfill(1, 1, ::magick::pixel.from_color(background))     end     # destroy_image(new_img)     filled.composite!(img, gravity, ::magick::overcompositeop)     # destroy_image(img)     # filled = yield(filled) if block_given?     # filled     filled.write new_img_path   end end 

Comments