ruby-on-rails-3 – Paperclip后期处理 – 如何使用jpegoptim / optpng压缩图像

我想使用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?还是安全的,我只是检查扩展字符串是否包含在该字符串中?

解决方法

既然没有其他的答案,这里是我在我的项目中做的,似乎它几个月的工作正常.
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,# :processors => [:image_compressor],: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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...