原创作者: hideto
阅读:1552次
评论:0条
更新时间:2011-05-26
今天来看看Rails怎样做Image的thumbnail
我们需要RMagick,它是ImageMagick/GraphicsMagick的Ruby API
我们先安装好ImageMagic/GraphicsMagick,然后安装RMagick:
上传表单:
Controller:
app/models/image.rb:
另外file_column插件有一些更高级的特性
我们需要RMagick,它是ImageMagick/GraphicsMagick的Ruby API
我们先安装好ImageMagic/GraphicsMagick,然后安装RMagick:
sudo gem install rmagick
上传表单:
<% form_fo :image, @image, url=> {:action => 'create'}, :html=>{:multipart=>true} do |f| %> <label for='image_name'>Name:</label> <%= f.text_field :name %><br/> <label for='image_file_data'>Image File:</label> <%= f.file_field :file_data %></br/> <label for='image_description'>Description:</label><br/> <%= f.text_area :description, :cols => 80, :rows => 5 %><br/> <% submit_tag "Save" %> <% end %>
Controller:
def create @image = Image.create params[:image] end
app/models/image.rb:
require 'RMagick' class Image < ActiveRecord::Base DIRECTORY = 'public/uploaded_images' THUMB_MAX_SIZE = [125, 125] after_save :process after_destroy :cleanup def file_date=(file_data) @file_data = file_data write_attribute 'extension', file_data.original_filename.split('.').last.downcase end def url path.sub(/^public/, '') end def thumbnail_url thumbnail_path.sub(/^public/, '') end def path File.join(DIRECTORY, "#{self.id}-full.#{extension}") end def thumbnail_path File.join(DIRECTORY, "#{self.id}-thumb.#{extension}") end ####### private ####### def process if @file_data create_directory cleanup save_fullsize create_thumbnail @file_data = nil end end def save_fullsize File.open(path, 'w') do |file| file.puts @file_data.read end end def create_thumbnail img = Magick::Image.read(path).first thumbnail = img.thumbnail(*THUMB_MAX_SIZE) thumbnail.write thumbnail_path def create_directory FileUtils.mkdir_p DIRECTORY end def cleanup Dir[File.join(DIRECTORY, "#{self.id}-*")].each do |filename| File.unlink(filename) rescue nil end end end
另外file_column插件有一些更高级的特性
评论 共 0 条 请登录后发表评论