我的rails应用程序使用Paperclip和ImageMagick处理上传的照片。
我目前已经设置了这样的
as_attached_file :photo, :styles => { :original => "1500x1500>", :thumb => "400x400>#", :large => "1080x1080>" }, :convert_options => { :thumb => '-quality 60', :large => '-quality 60'}, :default_url => "/missing.png"
如果有人上传尺寸为1000x100(纵横比为10:1)的图像,我想限制纵横比(在:large和:original上),这样如果纵横比太大,它会裁剪图像极端。
即:如果比率超过4:1或1:4,那么裁剪
答案 0 :(得分:0)
执行此操作的最佳方法是实现自定义处理器。这样,您就可以实现逻辑并决定何时以您希望的方式更改图像。
查看自定义处理器的示例实现。在我的情况下,我需要在图像上应用水印。
module Paperclip
class Watermark < Thumbnail
attr_accessor :format, :watermark_path, :watermark_gravity, :watermark_dissolve
def initialize file, options = {}, attachment = nil
super
@file = file
@format = options[:format]
@watermark_path = options[:watermark_path]
@watermark_gravity = options[:watermark_gravity].nil? ? "center" : options[:watermark_gravity]
@watermark_dissolve = options[:watermark_dissolve].nil? ? 40 : options[:watermark_dissolve]
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
end
def make
return @file unless watermark_path
dst = Tempfile.new([@basename, @format].compact.join("."))
dst.binmode
command = "composite"
params = "-gravity #{@watermark_gravity} -dissolve #{@watermark_dissolve} #{watermark_path} #{fromfile} #{tofile(dst)}"
begin
success = Paperclip.run(command, params)
rescue PaperclipCommandLineError
raise PaperclipError, "There was an error processing the watermark for #{@basename}"
end
dst
end
def fromfile
"\"#{ File.expand_path(@file.path) }[0]\""
end
def tofile(destination)
"\"#{ File.expand_path(destination.path) }[0]\""
end
end
end
has_attached_file :file,
processors: [:thumbnail, :watermark],
styles: {
layout: "100%",
preview: {geometry: "900x900>", watermark_path: "#{Rails.root}/app/assets/images/watermarks/watermark_200.png"},
thumbnail: "300x300>",
miniature: "150x150>"
},
convert_options: {
layout: "-units PixelsPerInch -density 100",
preview: "-units PixelsPerInch -density 72",
thumbnail: "-units PixelsPerInch -density 72",
miniature: "-units PixelsPerInch -density 72"
}
您可以参考自定义处理器的文档:
https://github.com/thoughtbot/paperclip#custom-attachment-processors