如何创建自定义的 Paperclip 处理器以获取图像尺寸 Rails 4

4

我希望在上传文件时获取图片的尺寸信息。我通过模型使用提取图像尺寸来实现这一点。但是,我想通过自定义处理器来完成这个任务。我尝试了以下代码:

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

我从这里获取了上面(custom.rb)的代码。 是否可能实现此目标?如何实现?谢谢提前 :)


你没有明确指出出了什么问题。使用Paperclip::Custom处理器得到了什么结果? - czak
值得一提的是,你提到的“参考资料”很可能是这个问题 - czak
@ŁukaszAdamczak:问题是它甚至没有进入自定义处理器。是的,你说得对,我只是从那个链接中得到了参考。让我更新一下。我从未尝试过模型之外的东西。但我必须仅通过自定义处理器来完成它。你能指导一下如何使用吗? - Gagan Gami
1个回答

11

我重现了您的情况,我相信原因是这里有一个拼写错误:

has_attached_file :avatar, processors: [:custom], :style => {:original => {}}
应该使用:styles而不是:style。没有:styles选项,paperclip将不进行任何后处理并忽略:processors
此外,这是一个非常简单的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

谢谢,这真的帮了我.. :) - Gagan Gami
2
".\#{options[:format]}" needs to be ".#{options[:format]}" - Roko
"no-:styles 忽略 :processors 的存在,对我来说非常合适!" - Andre Albuquerque

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接