2010-12-14 27 views
20

我最近使用Rails實現了Paperclip,並且想要嘗試ImageMagick中的一些過濾器選項,例如blur。我一直無法找到任何如何做到這一點的例子。它是否通過:風格作爲另一種選擇?Rails回形針如何使用ImageMagick的過濾器選項?

:styles => { :medium => "300x300#", :thumb => "100x100#" } 

@ plang的答案是正確的,但我想給到模糊的精確解,以防萬一有人在看着,發現這樣一個問題:

:convert_options => { :all => "-blur 0x8" } 
// -blur {radius}x{sigma} 

從而改變這一點:
alt text

對此:
alt text

回答

13

我沒有測試這一點,但你應該能夠使用「convert_options」參數,像這樣:

:convert_options => { :all => ‘-colorspace Gray’ } 

看一看https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/thumbnail.rb

我personnaly用我自己的處理器。

在型號:

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%,但它的工程!

+2

抱歉耽擱,感謝偉大的答案! – jyoseph 2010-12-17 02:24:50

+4

感覺好像在wayyy中更容易添加轉換選項 ':styles => {:gray =>「450x250」},:convert_options => {:gray =>「-blur 0x8」}' – Ben 2013-10-21 21:02:24

0

導軌5,回形針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 

然後就這樣在視圖中使用(每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) %>