class ImageService
require "mini_magick"
def self.tmp_dir
dir = "#{Rails.root}/tmp/image"
FileUtils.mkdir(dir) unless File.exists?(dir)
dir
end
def self.composite(image_paths)
to_path = "#{tmp_dir}/composite_#{SecureRandom.uuid.to_s.strip}.jpeg"
montage_commond = image_paths + ["-strip", "-quality", "70", "-tile", "1x#{image_paths.length}", "-geometry", "+0+0", to_path]
MiniMagick::Tool::Montage.new{|m| m.merge! montage_commond}
to_path
end
def self.compress(image_path, watermark = false)
to_path = "#{tmp_dir}/compress_#{SecureRandom.uuid.to_s.strip}.jpeg"
image = MiniMagick::Image.open image_path
image.combine_options do |b|
b.strip
b.quality "60"
end
if watermark
watermark_image = MiniMagick::Image.open("#{Rails.root}/app/assets/images/special_watermark.png")
watermark_width = (image.width * 0.9).to_i
watermark_height = (watermark_image.height * (watermark_width / watermark_image.width.to_f)).to_i
watermark_image.resize "#{watermark_width}x#{watermark_height}"
image = image.composite(watermark_image) do |c|
c.gravity 'center'
end
end
image.write to_path
to_path
end
end
图片合并
image_paths = files.map{|f| f.tempfile.path}
composite_path = ImageService.composite(image_paths)
File.open(composite_path) do |f|
attachment.path = f
end
文件格式大小限制
def create_company_change
files = params[:file_path]
flag, flash[:msg] = check_file(files)
unless flag
redirect_to my_whmall_account_informations_url and return
else
#todo
end
end
def check_file(files)
max_size = 1024 * 1024 * 3 #3M
file_type = ['image/gif ', 'image/png', 'image/jpeg', 'application/pdf']
return false, '上传文件不能为空' if files.blank?
files.each do |file|
return false, '文件不能大于3M' if file.size > max_size
return false, '可上传的图片格式将限于jpg、gif、png和pdf' unless file_type.include? file.content_type
end
return true, '变更申请提交成功,请等待审核。'
end