attachment_fuでサイズを変更するflickrスタイル
-
20-09-2019 - |
質問
Attachment_FUに、Flickr、Facebook、Twitterがこれを処理する方法と同様の方法でサムネイルをサイズ変更してもらいたいです。100x100サムネイルが必要な場合は、サムネイルを100x100にして、アスペクト比が保持されるように過剰にクロップしています。
何か案は?
解決 4
私の解決策は、attachment_fuプラグインフォルダー(ベンダー/プラグイン)を掘り下げ、rmagick_processor.rbファイルを編集することでした。最初にsezize_imageをsezize_image_internalに変更し、次のように変更しました。
def resize_image(img, size)
# resize_image take size in a number of formats, we just want
# Strings in the form of "square: WxH"
if (size.is_a?(String) && size =~ /^square: (\d*)x(\d*)/i) ||
(size.is_a?(Array) && size.first.is_a?(String) &&
size.first =~ /^square: (\d*)x(\d*)/i)
iw, ih = img.columns, img.rows
aspect = iw.to_f / ih.to_f
if aspect > 1
shave_off = (iw - ih) / 2
img.shave!(shave_off, 0)
else
shave_off = (ih-iw) / 2
img.shave!(0, shave_off)
end
resize_image_internal(img, "#{$1}x#{$2}!")
else
resize_image_internal(img, size) # Otherwise let attachment_fu handle it
end
end
これで、「Square:100x100」を幾何学的な文字列として使用できます。上記のコードは、必要な出力が正方形であると想定していることに注意してください。
他のヒント
100x100のサムネイルをセットアップするには、モデルに次のものを追加します。
has_attachment :content_type => :image,
:storage => IMAGE_STORAGE,
:max_size => 20.megabytes,
:thumbnails => {
:thumb => '100x100>',
:large => '800x600>',
}
(この例では、元のサイズを維持するために、100x100のサムネイルと800x600の「大きな」サイズを作成しています。)
また、サムネイルは正確に100x100ではない可能性があることに留意してください。最大寸法は100x100です。これは、オリジナルのアスペクト配分が4:3の場合、サムネイルは100x75になることを意味します。 「アスペクト比が維持されるように、余分なクロップがオフになっているという正確な100x100」という意味であるかどうかは正確にはわかりません。
これをモデルに追加します
protected
# Override image resizing method
def resize_image(img, size)
# resize_image take size in a number of formats, we just want
# Strings in the form of "crop: WxH"
if (size.is_a?(String) && size =~ /^crop: (\d*)x(\d*)/i) ||
(size.is_a?(Array) && size.first.is_a?(String) &&
size.first =~ /^crop: (\d*)x(\d*)/i)
img.crop_resized!($1.to_i, $2.to_i)
# We need to save the resized image in the same way the
# orignal does.
self.temp_path = write_to_temp_file(img.to_blob)
else
super # Otherwise let attachment_fu handle it
end
end
サムネイルサイズを次のように変更します。
:thumbnails => {:thumb => 'crop: 100x100' }
ソース:
http://stuff-things.net/2008/02/21/quick-and-dirty-cropping-images-with-attachment_fu/
仕様に記載できるトリミング指令があります。
has_attachment :content_type => :image,
:thumbnails => {
:thumb => '100x100#'
}
メモニック: '#'は作物のツールのように見えます。
編集: 修正
has_attachment :content_type => :image,
:thumbnails => {
:thumb => '100x100!'
}
以前の方法は、異なる表記を持つPaperClip用でした。