Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Custom Paperclip Processor to retrieve image dimensions Rails 4

I want to retrieve image upload dimensions before create as I attach the file. I got this via Extracting Image dimensions through model. But I want to dispatch through custom processor. What I tried is: 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

I got the above (custom.rb) code from here. Is it possible to achieve is? How? Thanks in advance :)

like image 285
Gagan Gami Avatar asked Dec 19 '22 07:12

Gagan Gami


1 Answers

I reproduced your case and I believe the cause is the typo here:

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

It should be :styles instead of :style. Without a :styles option, paperclip does not do any post-processing and ignores your :processors.

Also, here is a very simple implementation of a Paperclip::Processor - turns attachments into grayscale. Replace the command inside convert to perform your own post-processing:

# 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
like image 128
czak Avatar answered Apr 26 '23 20:04

czak