【问题标题】:How to create Custom Paperclip Processor to retrieve image dimensions Rails 4如何创建自定义回形针处理器以检索图像尺寸 Rails 4
【发布时间】:2023-10-24 10:11:01
【问题描述】:

我想在附加文件时在创建之前检索图像上传尺寸。我通过模型通过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

我从here 获得了上述(custom.rb)代码。 有没有可能实现的是?如何?在此先感谢:)

【问题讨论】:

  • 你没有澄清什么是真正的错误。你用这个Paperclip::Custom 处理器得到了什么结果?
  • 另外值得一提的是,您提到的作为来源的“参考”很可能是this question
  • @ŁukaszAdamczak :问题是它甚至没有进入自定义处理器。是的,您是对的,仅从该链接获得了参考。让我更新。我从来没有尝试过模型。但我只能通过自定义处理器来完成。能指导一下怎么用吗??

标签: ruby-on-rails ruby paperclip dimensions processor


【解决方案1】:

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

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

应该是:styles 而不是:style。如果没有 :styles 选项,回形针不会进行任何后处理并忽略您的 :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

【讨论】:

  • 谢谢你,它真的对我有帮助.. :)
  • ".\#{options[:format]}" 必须是 ".#{options[:format]}"
  • no-:styles 忽略了:processors 的存在对我来说是正确的!