rails, image upload and resize with imagemagik
I开发者_C百科 made a small piece of code to upload a file and then resize it with imagemagik. I am using the system("command") function to call imagemagik to resize the image, but the output is a file of size 0 bytes. any idea what could be going wrong?
I would suggest using RMagick, which is a ruby wrapper around imagemagick. It will help keep things more ruby-like, and is generally useful to know.
Google will help (or stackoverflow for RMagick), but the steps are something like (I'm assuming Rails 3):
in application.config:
gem 'rmagick'
Then, in your controller:
require 'RMagick'
def create
@upload_io = params[:image_field]
@filename = @upload_io.original_filename
@filepath = Rails.root.join('public', 'images', @filename)
File.open(@filepath) do |file|
file.write(image_io.read)
end
@original = Magick::Image.read(@filepath)
@thumbnail = @original.resize_to_fit 75 75
@thumbnail.write(Rails.root.join('public', 'images', 'sm_' + filename)
end
If you're not so keen on RMagick, I would also suggest making sure you're saving your file before resizing it (does the original exist?), and make sure that your paths are consistent and that you're actually hitting the right spot on the file system.
精彩评论