Search code examples
ruby-on-railsrubyimagemagickimagemagick-convertminimagick

MiniMagick: make a square


I do this:

begin
  image = MiniMagick::Image.open(params[:avatar_file].path)
  unless image.valid?
    raise nil
  end
rescue
  return head :not_acceptable
end
image.format 'jpeg'
image.resize '128x128'
image.write dir.to_s + current_user.id.to_s + '_128x128.jpg'

And after the resizing, if an image wasn't a square, one of the sides has 128 pixels and the second is smaller than the first.

I would like to make them the same size by cropping the center of the image.

As far as I know, "convert" utility of ImageMagick has "gravity center", but I'm not sure that this is what I need and how to use it with MiniMagick.


Solution

  • The answer is in the image.combine_options block:

    begin
      image = MiniMagick::Image.open(params[:avatar_file].path)
      unless image.valid?
        raise nil
      end
    rescue
      return head :not_acceptable
    end
    image.format 'jpeg'
    image.combine_options do |c|
      c.resize '128x128^'
      c.gravity 'center'
      c.extent '128x128'
    end
    image.write dir.to_s + current_user.id.to_s + '_128x128.jpg'
    

    ImageMagick variant:

    convert stock.jpg -resize 128x128^ -gravity center -extent 128x128 result.jpg