LoginSignup
17
17

More than 5 years have passed since last update.

RMagickで画像を正方形に加工したmemo

Posted at

ユーザーがプロフィール画像をアップロードする機能を実装するとき、
下記の要件を満たしたかった。

・画像の形式指定、画像のサイズ最大値指定
・画像のトリミング、縮小

まず、ImageMagickをインストール
brew install imagemagick or yum install imagemagick

Gemfileに下記追加
gem 'rmagick' その後 bundle install

ざっくりこんな感じで処理できる。
file = params[:users][:image] #フォームからアップロードされた画像
thumb = Magick::Image.from_blob(file.read).shift
thumb_out = thumb.resize_to_fill!(120, 120).to_blob

ちなみに形式とサイズ最大値のバリデーションはこんな感じ。
file.content_type =~ /^image/ && file.size < 2048.kilobytes

参考URL
http://morizyun.github.io/blog/rmagic-square-thumbnail-ruby/
http://blog.ruedap.com/2011/03/20/mac-ruby-imagemagick-rmagick-install

17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17