最善の解決策は、300x300 の白いキャンバス イメージを作成し、そのイメージをキャンバス イメージの上に中央揃えで合成することです。次に、重心(中央揃え)でトリミングします。これにより、寸法が 300 より小さい縦または横のエッジに白いキャンバスがある 300x300 の画像が生成されます。
** このソリューションでは、必要な ImageMagick 操作が Dragonfly によって拡張されているとは思えないため、RMagick gem をインストールする必要がある場合があります。
これは私がそれにアプローチする方法です:
#Set file path first and load a white image called canvas that is 300x300 into Imagmagik
canvas_file_path = "#{Rails.root}/app/assets/images/canvas.png"
canvas_image = Magick::Image.read(canvas_file_path).first
#Then perform the compositing operation. This overlays your image on top of the canvas, center gravity ensures that your image is centered on the canvas.
canvas_image.composite!(<YOUR IMAGE>, CenterGravity, Magick::OverCompositeOp)
#then write the file to a temporary file path so you can do something with it
temporary_file_path = "#{Rails.root}/tmp/#{@model.id}"
canvas_image.write(temporary_file_path)
必ずファイルに require ステートメントを追加してください。大文字と小文字の区別に細心の注意を払ってください。Rmagick ではなく RMagick です。
require "RMagick"
参考までに、必要な合成操作を実行するためのドキュメントの ImageMagick の例を次に示します。
composite -gravity center smile.gif rose: rose-over.png
画像を合成する方法に関する Rmagick ドキュメント - http://www.imagemagick.org/RMagick/doc/image1.html#composite
Rmagick ジェム - https://github.com/rmagick/rmagick
合成に関する ImageMagick リファレンス - http://www.imagemagick.org/script/composite.php