2014-03-02 50 views
0

我的rails应用程序使用Paperclip和ImageMagick处理上传的照片。根据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的纵横比),例如我想限制纵横比(对:大和:original),这样如果纵横比太高,它会裁剪图像。

即:如果比值超过4:1或1:4,然后裁剪

回答

0

要做到这一点,最好的方法是实现自定义处理器。这样您就可以实现自己的逻辑并根据需要决定何时更改图像。

查看自定义处理器的示例实现。在我的情况下,我需要在图像上应用水印。

的lib/paperclip_processors/watermark.rb

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 

型号/ image.rb

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

相关问题