基于mini_magick多图片合并/添加水印

本文介绍了一种图片处理服务,该服务使用Ruby编程语言实现图片的合并与压缩功能。通过利用`mini_magick` gem,文章详细展示了如何创建临时目录存放图片、如何使用Montage进行图片合并以及如何对图片进行压缩并添加水印。此外,还定义了文件上传时的格式与大小限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值