纸夹后处理 - 如何使用jpegoptim/optpng压缩图像

13

我希望使用jpegoptim或者optipng来压缩用户通过Paperclip上传的图片。

我的Paperclip模型已经配置好了:

  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"

问题1: 用户上传的原始图像是否可以进行压缩,然后让Paperclip调整大小,使得只需要一个压缩过程?怎么做?

问题2: 我将通过after_post_process回调来完成此操作,并且可以从image.queued_for_write获得所有三个文件的实例,我想按文件扩展名触发jpegoptim/optipng,但是当我使用current_format = File.extname(file.path)时,我得到类似于:.jpg20120508-7991-cqcpf2。有没有办法获取扩展名字符串jpg?或者直接检查该字符串是否包含在扩展名字符串中是否安全?


@CharlieMezak 我把我自己的答案粘贴了上去,因为没有其他答案。我可能不是最好的,如果你对此有任何意见,我非常乐意听取。谢谢。 - larryzhao
3个回答

4

由于没有其他答案,下面是我在项目中的做法,看起来已经正常工作了几个月。

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

2

1
可能会有性能上的妥协,但我使用FFMPEG或AVCONV得到了更好压缩的图像。
sudo apt-get install ffmpeg

= 初始化器

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

= 模态框

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

我把一个1.7MB的图像压缩到了302.9KB!!!


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