项目地址: https://github.com/jnicklas/carrierwave
gem 'carrierwave', "0.6.2"
bundle install
rails generate uploader Video生成uploader文件
如果需要处理图片,可增加Minimagick gem
gem 'mini_magick', "3.3"修改uploader
include CarrierWave::MiniMagick
# Create different versions of your uploaded files:
version :thumb do
process resize_to_fill: [150, 150]
end
version :main do
process resize_to_fill: [600, 400]
end
version :cif do
process resize_to_fill: [320, 240]
end生成model
rails g scaffold video title:string file:string message_id:integer deleted:boolean user_id:integerake db:migratebootstrap 格式化Html
rails g bootstrap:themed Videos修改video model
mount_uploader :file, VideoUploader引用
u.avatar.url # => '/url/to/file.png'
u.avatar.current_path # => 'path/to/file.png'
u.avatar.identifier # => 'file.png'修改form表单
<%= form_for @user, :html => {:multipart => true} do |f| %>
<% end %>修改图片大小的方法
def resize_to_limit(width, height)
process :resize_to_limit => [width, height]
end
def resize_to_fit(width, height)
process :resize_to_fit => [width, height]
end
def resize_to_fill(width, height, gravity='Center')
process :resize_to_fill => [width, height, gravity]
end
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
process :resize_and_pad => [width, height, background, gravity]
endresize_to_limit 保存图片完整性
resize_to_fill 图片大小优先
一个需求:
限制width: 320, 高度任意
process :resize_fo_limit: [320, '']

本文介绍如何使用CarrierWave处理图片上传,包括安装配置、图片版本创建及尺寸调整方法。同时,展示了如何集成MiniMagick以实现图片的多种格式转换。
557

被折叠的 条评论
为什么被折叠?



