0
votes

My rails app uses Paperclip and ImageMagick to process uploaded photos.

I currently have it set up like this

as_attached_file :photo, :styles => { :original => "1500x1500>", :thumb => "400x400>#", :large => "1080x1080>" }, :convert_options => { :thumb => '-quality 60', :large => '-quality 60'},  :default_url => "/missing.png"

If someone uploads an image with dimension 1000x100 (10:1 aspect ratio) for example I would like to limit the aspect ratio (on the :large and :original) so that it will crop the image if the aspect ratio is too extreme.

ie: if ratio is beyond 4:1 or 1:4 then crop

1

1 Answers

0
votes

The best way to do this is to implement a custom processor. That way you can implement your logic and decide when to change the image the way you want.

See an example implementation of a custom processor. In my case I needed to apply a watermark on the images.

lib/paperclip_processors/watermark.rb

module Paperclip
  class Watermark < Thumbnail

    attr_accessor :format, :watermark_path, :watermark_gravity, :watermark_dissolve

    def initialize file, options = {}, attachment = nil
      super
      @file               = file
      @format             = options[:format]
      @watermark_path     = options[:watermark_path]
      @watermark_gravity  = options[:watermark_gravity].nil? ? "center" : options[:watermark_gravity]
      @watermark_dissolve = options[:watermark_dissolve].nil? ? 40 : options[:watermark_dissolve]

      @current_format     = File.extname(@file.path)
      @basename           = File.basename(@file.path, @current_format)
    end

    def make
      return @file unless watermark_path

      dst = Tempfile.new([@basename, @format].compact.join("."))
      dst.binmode

      command = "composite"
      params = "-gravity #{@watermark_gravity} -dissolve #{@watermark_dissolve} #{watermark_path} #{fromfile} #{tofile(dst)}"

      begin
        success = Paperclip.run(command, params)
      rescue PaperclipCommandLineError
        raise PaperclipError, "There was an error processing the watermark for #{@basename}"
      end

      dst
    end

    def fromfile
      "\"#{ File.expand_path(@file.path) }[0]\""
    end

    def tofile(destination)
      "\"#{ File.expand_path(destination.path) }[0]\""
    end

  end
end

models/image.rb

has_attached_file :file,
processors: [:thumbnail, :watermark],
styles: {
layout:    "100%",
preview:   {geometry: "900x900>", watermark_path: "#{Rails.root}/app/assets/images/watermarks/watermark_200.png"},
thumbnail: "300x300>",
miniature: "150x150>"
},
convert_options: {
layout:    "-units PixelsPerInch -density 100",
preview:   "-units PixelsPerInch -density 72",
thumbnail: "-units PixelsPerInch -density 72",
miniature: "-units PixelsPerInch -density 72"
}

You can refer to the documentation for custom processors:

https://github.com/thoughtbot/paperclip#custom-attachment-processors