Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip post process - How to compress image using jpegoptim/optpng

I would like to use jpegoptim or optipng to compress the image uploaded by users via Paperclip.

I have a Paperclip model configured as:

  has_attached_file :image,
                    :styles => {:thumb => '50x50>', :preview => '270x270>' },
                    :url => "/system/:class/:attachment/:id/:basename_:style.:extension",
                    :path => ":rails_root/public/system/:class/:attachment/:id/:basename_:style.:extension"

Question 1: Is it possible to compress the original image uploaded by user, then let Paperclip resize it , so there's only one compress process? and how to do it?

Question 2: I am going to do it via the after_post_process callback, and I could get all the instances of three files from image.queued_for_write and I would like to trigger jpegoptim/optipng by the file extension, but when I use current_format = File.extname(file.path), I get something like: .jpg20120508-7991-cqcpf2. Is there away to get the extension string jpg? or is it safe that I just check if the extension string is contained in that string?

like image 629
larryzhao Avatar asked May 08 '12 08:05

larryzhao


3 Answers

Since there's no other answers, here is how I do it in my project and it seems it's being working ok for several months.

class AttachedImage < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true

  validates_attachment_presence :image
  validates_attachment_content_type :image, :content_type=>['image/jpeg', 'image/png', 'image/gif']

  has_attached_file :image,
                    :styles => {:thumb => '50x50>', :preview => '270x270>' },
                    # :processors => [:image_compressor],
                    :url => "/system/:class/:attachment/:id/:basename_:style.:extension",
                    :path => ":rails_root/public/system/:class/:attachment/:id/:basename_:style.:extension"


  after_post_process :compress

  private
  def compress
    current_format = File.extname(image.queued_for_write[:original].path)

    image.queued_for_write.each do |key, file|
      reg_jpegoptim = /(jpg|jpeg|jfif)/i
      reg_optipng = /(png|bmp|gif|pnm|tiff)/i

      logger.info("Processing compression: key: #{key} - file: #{file.path} - ext: #{current_format}")

      if current_format =~ reg_jpegoptim
        compress_with_jpegoptim(file)
      elsif current_format =~ reg_optipng
        compress_with_optpng(file)
      else
        logger.info("File: #{file.path} is not compressed!")
      end
    end
  end

  def compress_with_jpegoptim(file)
    current_size = File.size(file.path)
    Paperclip.run("jpegoptim", "-o --strip-all #{file.path}")
    compressed_size = File.size(file.path)
    compressed_ratio = (current_size - compressed_size) / current_size.to_f
    logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}")
    logger.debug("JPEG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%")
  end

  def compress_with_optpng(file)
    current_size = File.size(file.path)
    Paperclip.run("optipng", "-o7 --strip=all #{file.path}")
    compressed_size = File.size(file.path)
    compressed_ratio = (current_size - compressed_size) / current_size.to_f
    logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}")
    logger.debug("PNG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%")   
  end                              
end
like image 121
larryzhao Avatar answered Jan 14 '23 22:01

larryzhao


There are also some gems to optimize paperclip images:

  • paperclip-optimizer
  • paperclip-compressor
like image 32
mahemoff Avatar answered Jan 14 '23 23:01

mahemoff


Might be a performance compromise but I got images better compressed with FFMPEG or AVCONV.

sudo apt-get install ffmpeg

= initializer

Paperclip.options[:command_path] = "/usr/bin/" # see `which ffmpeg`

= Modal

after_save :compress_with_ffmpeg

def compress_with_ffmpeg
  [:thumb, :original, :medium].each do |type|
    img_path = self.avtar.path(type)
    Paperclip.run("ffmpeg", " -i #{img_path} #{img_path}")
  end
end

I got 1.7MB image compressed to 302.9KB!!!

like image 35
Moin Haidar Avatar answered Jan 14 '23 22:01

Moin Haidar