In my Rails app I can upload images and the meta data is saved in the database table and the file written to disk fine (uploading handled by attachment_fu).
This works fine and I can display a user's avatar, however, I am using a jQuery plugin on the upload form to allow users to crop the image before it's uploaded so in my form POST
data I have the image and x
, y
, w
and h
parameters.
I then try and use these to crop the uploaded image but the new image created by RMagick is a 1x1 empty picture, I have hardcoded the image paths below to eliminate that as a possible issue, the image being read definitely exists as otherwise the app would throw an error.
# top of controller
require 'RMagick'
include Magick
def change_avatar
image = Magick::Image.read(RAILS_ROOT + '/public/files/avatars/0000/0027/940.jpg').first
cropped_image = image.crop(params[:x].to_i, params[:y].to_i, params[:w].to_i, params[:h].to_i, true).write(RAILS_ROOT + '/public/files/avatars/0000/0027/940_1.jpg')
redirect_to '/portal/profile/' + a.id.to_s
end
FYI, Ruby 1.8.7 and Rails 2.3.14
Update
After a lot of messing around I've realised the cropping and over-writing only works from reading a certain uploaded image:
image = Magick::Image.read(RAILS_ROOT + '/public/files/avatars/0000/0001/940.jpg').first
BUT
even if I change that to
image = Magick::Image.read(RAILS_ROOT + '/public/files/avatars/0000/0007/940.jpg').first
which is the same image that has been uploaded twice (well, more than that but just pointing out that I'm using the same image for testing purposes), the re-written file is saved as a 1 x 1 blank/empty image.
Both have the same permissions but don't think that's a factor since the image is actually being saved, no idea how it only works for this one particular image.
update 2
Think I've got it, in the model, attachment_fu
was resizing the uploaded image to 200 x 200 so instead of the cropping being applied to the uploaded image I think it was being applied to the cropped version so I think that was messing up something somewhere and resulted in a 1 x 1 image.
tldr: removed :resize_to => '200x200',
from the model.