我最近使用Rails实现了Paperclip,并希望尝试使用ImageMagick中的一些过滤器选项,例如blur。我无法找到任何如何做到这一点的例子。它是否通过了:样式作为另一种选择?
:styles => { :medium => "300x300#", :thumb => "100x100#" }
@ plang的答案是正确的,但我想给出模糊的确切解决方案,以防万一有人在寻找并发现这个问题:
:convert_options => { :all => "-blur 0x8" }
// -blur {radius}x{sigma}
这改变了这个:
对此:
答案 0 :(得分:13)
我没有对此进行测试,但您应该可以使用“convert_options”参数,如下所示:
:convert_options => { :all => ‘-colorspace Gray’ }
查看https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/thumbnail.rb
我个人使用自己的处理器。
在模特:
has_attached_file :logo,
:url => PaperclipAssetsController.config_url,
:path => PaperclipAssetsController.config_path,
:styles => {
:grayscale => { :processors => [:grayscale] }
}
在lib中:
module Paperclip
# Handles grayscale conversion of images that are uploaded.
class Grayscale < Processor
def initialize file, options = {}, attachment = nil
super
@format = File.extname(@file.path)
@basename = File.basename(@file.path, @format)
end
def make
src = @file
dst = Tempfile.new([@basename, @format])
dst.binmode
begin
parameters = []
parameters << ":source"
parameters << "-colorspace Gray"
parameters << ":dest"
parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ")
success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path))
rescue PaperclipCommandLineError => e
raise PaperclipError, "There was an error during the grayscale conversion for #{@basename}" if @whiny
end
dst
end
end
end
对于简单的灰度转换,这可能不是100%,但它可以工作!
答案 1 :(得分:0)
Rails 5,Paperclip 5更新
现在,您只需呼叫系统上的ImageMagick's convert command即可使用其grayscale option,而无需立即添加库。您可以对模糊或任何其他ImageMagick选项执行相同操作,但我需要执行此操作以转换为灰度。
在您的模型中(具有徽标的客户端):
class Client < ApplicationRecord
has_attached_file :logo,
styles: { thumb: "243x243#", grayscale: "243x243#" }
# ensure it's an image
validates_attachment_content_type :logo, content_type: /\Aimage\/.*\z/
# optional, just for name and url to be required
validates :name, presence: true
validates :url, presence: true
after_save :convert_grayscale
def convert_grayscale
system "convert #{self.logo.path(:thumb)} -grayscale Rec709Luminance #{self.logo.path(:grayscale)}"
end
def logo_attached?
self.logo.file?
end
end
然后在这样的视图中使用(per Paperclips github docs)。
在您看来:
<%= image_tag(client.logo.url(:grayscale), class: 'thumbnail', alt: client.name, title: client.name) %>
或者如果您愿意,可以使用链接:
<%= link_to(image_tag(client.logo.url(:grayscale), class: 'thumbnail', alt: client.name, title: client.name), client.url ) %>