当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – 如何创建自定义回形针处理器以检索图像尺寸Rails 4

来源:互联网 收集:自由互联 发布时间:2021-06-23
我希望在创建之前检索图像上传维度,因为我附加了文件.我通过模型通过 Extracting Image dimensions得到了这个.但我想通过自定义处理器发送.我尝试的是: Player.rb class Player ActiveRecord::Base
我希望在创建之前检索图像上传维度,因为我附加了文件.我通过模型通过 Extracting Image dimensions得到了这个.但我想通过自定义处理器发送.我尝试的是:
 Player.rb

class Player < ActiveRecord::Base
  has_attached_file :avatar, processors: [:custom], :style => {:original => {}}
....
end

/lib/paperclip_processors/custom.rb

module Paperclip
  class Custom < Processor
    def initialize file, options = {}, attachment = nil
      super
      @file           = file
      @attachment     = attachment
      @current_format = File.extname(@file.path) 
      @format         = options[:format]
      @basename       = File.basename(@file.path, @current_format)
    end

    def make
      temp_file = Tempfile.new([@basename, @format])
      #geometry = Paperclip::Geometry.from_file(temp_file)
      temp_file.binmode

      if @is_polarized
        run_string =  "convert #{fromfile} -thumbnail 300x400  -bordercolor white -background white  +polaroid  #{tofile(temp_file)}"    
        Paperclip.run(run_string)
      end

      temp_file
    end

    def fromfile
      File.expand_path(@file.path)
    end

    def tofile(destination)
      File.expand_path(destination.path)
    end
  end
end

我从this source获得了这个(custom.rb)代码.
这可能是我想要实现的目标吗?怎么样?我帮我错误吗?提前致谢 :)

我复制了你的案子,我相信原因是这里的错字:

has_attached_file :avatar, processors: [:custom], :style => {:original => {}}

它应该是:样式而不是:样式.如果没有:styles选项,paperclip不会进行任何后处理并忽略您的:处理器.

此外,这是一个非常简单的Paperclip :: Processor实现 – 将附件转换为灰度.替换convert中的命令以执行您自己的后处理:

# lib/paperclip_processors/custom.rb
module Paperclip
  class Custom < Processor
    def make
      basename = File.basename(file.path, File.extname(file.path))
      dst_format = options[:format] ? ".\#{options[:format]}" : ''

      dst = Tempfile.new([basename, dst_format])
      dst.binmode

      convert(':src -type Grayscale :dst',
              src: File.expand_path(file.path),
              dst: File.expand_path(dst.path))

      dst
    end
  end
end
网友评论