Return to Snippet

Revision: 3740
at September 9, 2007 15:43 by Tricon


Initial Code
require 'RMagick'
class Profile < ActiveRecord::Base
  belongs_to :user
  
  #image = the image passed from params[:image]
  #file_type = the confirmed filetype from the controller
  #current_user = various information about the current user
  def self.upload(image, file_type, current_user)
    #set default cols and rows for our two images that will be created from the uploaded user image
    img_size = {:main =>{:cols => 250,:rows => 375},
          :thumb =>{:cols =>80, :rows =>120}
         }
    #set base directory for the users image
    imgDir = "#{RAILS_ROOT}/public/images/user_images"
    #set the base name for our userimage
    userImg = " #{current_user.login}-#{current_user.id}"
    #loop through the image dir and delete any old user images
    Dir.foreach(imgDir){|file|
    if file.to_s.include?(userImg)
      File.unlink("#{imgDir}/#{file}")
    end
    }
    #read the image from the string
    imgs = Magick::Image.from_blob(image.read)
    #change the geometry of the image to suit our predefined size
    main_image = imgs.first.change_geometry!("#{img_size[:main][:cols]}x#{img_size[:main][:rows]}") { |cols, rows, img|
       #if the cols or rows are smaller then our predefined sizes we build a white background and center the image in it
     if cols < img_size[:main][:cols] || rows < img_size[:main][:rows]
      #resize our image 
      img.resize!(cols, rows)
      #build the white background
      bg = Magick::Image.new(img_size[:main][:cols],img_size[:main][:rows]){self.background_color = "white"}
      #center the image on our new white background
      bg.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)

     else
      #in the unlikely event that the new geometry cols and rows match our predefined size we will not set a white bg
        img.resize!(cols, rows)
     end
      }
    main_image.write "#{imgDir}/#{userImg}.#{file_type}"

    thumb = imgs.first.change_geometry!("#{img_size[:thumb][:cols]}x#{img_size[:thumb][:rows]}") { |cols, rows, img|
       if cols < img_size[:thumb][:cols] || rows < img_size[:thumb][:rows]
      img.resize!(cols, rows)
      bg = Magick::Image.new(img_size[:thumb][:cols],img_size[:thumb][:rows]){self.background_color = "white"}
      bg.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)

     else
        img.resize!(cols, rows)
     end
      }
    thumb.write "#{imgDir}/#{userImg}-thumb.#{file_type}"
    if FileTest.exist?("#{imgDir}/#{userImg}.#{file_type}")
    return "The file was written and its name is #{userImg}.#{file_type}"
    else
    return false
    end
  end
end

Initial URL
http://pastie.caboo.se/95581

Initial Description
Use this to upload and resize your images using RMagick. Code by nixnewbie.

Initial Title
Upload and resize with RMagick

Initial Tags
resize, rails, ruby

Initial Language
Rails