Gem carrierwave 使用时间戳重命名文件以及在 version 中动态指定图片尺寸

zouyu · 2016年02月27日 · 1852 次阅读

以下是在项目中做图片上传遇到的需求以及解决方案

1. 使用时间戳重新命名上传的文件

def filename
   @name ||= "#{timestamp}.#{file.extension.downcase}" if original_filename.present? and super.present?
 end


 def timestamp
   var = :"@#{mounted_as}_timestamp"
   model.instance_variable_get(var) or model.instance_variable_set(var, Time.zone.now.strftime('%Y%m%d%H%M%S'))
 end

参考 https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Use-a-timestamp-in-file-names

2. version 中动态指定图片尺寸

原图需要根据指定的宽,计算实际生成图片时的高

version :demo do
    process :calculate_demo => 1242
  end

def calculate_demo(standard_width)
    standard_width = standard_width.to_f
    file_dimensions = ::MiniMagick::Image.open(file.file)[:dimensions]#[width, height]#使用MiniMagick获取原始图片宽度
    standard_height = (standard_width * file_dimensions[1] / file_dimensions[0]).to_i
    resize_to_fit standard_width.to_i, standard_height
  end

参考 1.获取图片的维度 1.http://www.diowa.com/blog/rails/2014/03/22/using-one-carrierwave-image-uploader-with-dynamic-versions/

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号