每天一剂Rails良药之Processing Uploaded Images

今天来看看Rails怎样做Image的thumbnail
我们需要 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插件有一些更高级的特性

你可能感兴趣的:(F#,Ruby,ActiveRecord,Rails,OpenSource)