views:

454

answers:

2

I'm creating a little photo sharing site for our home's intranet, and I have an upload feature, which uploads the photo at original size into the database. However, I also want to save the photo in four other sizes: W=1024, W=512, W=256 and W=128, but only the sizes smaller than the original size (e.g. if the original width is 511, only generate 256 and 128). The image with a width of 128 should always be generated (because it's a thumbnail). Also, the resization should always be with a proportional width and height. How can I implement this? I already have this code to upload the photo:

pic.rb <-- model

def image_file=(input_data)
  self.filename     = input_data.original_filename
  self.content_type = input_data.content_type.chomp
  self.binary_data  = input_data.read
  # here it should generate the smaller sizes
  #+and save them to self.binary_data_1024, etc...
end

new.rb <-- view

<h1>New pic</h1>

<% form_for(@pic, :html => {:multipart => true}) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :description %><br />
    <%= f.text_field :description %>
  </p>
  <p>
    <%= f.label :image_file %><br />
    <%= f.file_field :image_file %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', pics_path %>

Thanks

+3  A: 

Simply use paperclip or attachment_fu

denisjacquemin
Paperclip did the job =D
Time Machine
+2  A: 

You can resize with RMagick gem.

This is just a example that you can adapt:

require 'RMagick'

f = File.new( File.join(save_path, self.filename), "wb"  )
f.write form_file.read #remeber to set :html=>{:multipart => true} in form
f.close

image = Magick::Image.read(self.filename).first
image.change_geometry!("640x480") { |cols, rows, img|
    newimg = img.resize(cols, rows)
    newimg.write("newfilename.jpg")
}

More Info here: http://www.imagemagick.org/RMagick/doc/

Sebtm