2010-03-08 35 views
0

這是關於使用Ruby On Rails的RMagick。RMAGICK:改變圖片的文件類型(動態)...不正確的圖片頭錯誤

我做到以下幾點:

image = params[:image] 
    # params[:image] is the image from the file-form. 
    name = image.original_filename.scan(/[^\/\\]+/).last 
    name = dir + t.day.to_s + t.month.to_s + t.year.to_s + t.hour.to_s + t.min.to_s + t.sec.to_s + name 
    f = File.new(name, "wb") 
    f.write image 
    f.close 
    image = Magick::Image.read(name) 
    image = image.resize_to_fit(200, 250) 
    f = File.new(name, "wb") 
    f.write image.to_blob 
    f.close 

我真的需要先保存,然後改變它呢? 如何改變不僅尺寸,改變文件類型?我想要一個60%質量的JPG。

這個錯誤是什麼意思?

Magick::ImageMagickError (Improper image header `public/images/avatars/Joern/83201018458ich2_kleiner.png'): 

請幫幫我。

你的, Joern。

回答

0

興趣的人,這是解決方案:

t = Time.now 
    if !File.directory?(dir = "public/images/avatars/#{self.current_user.login}/") 
    Dir.mkdir(dir) 
    end 
    image = params[:image] 
    basename = t.day.to_s + t.month.to_s + t.year.to_s + t.hour.to_s + t.min.to_s + t.sec.to_s + ".jpg" 
    name = dir + basename 
    image = Magick::Image.from_blob(image.read).last 
    image = image.resize_to_fit(200, 250) 
    image.write(name) do self.quality = 60 end 
    picture = Picture.new 
    picture.path = "avatars/" + self.current_user.login + "/" + basename 
    picture.user_id = self.current_user.id 
    picture.save 
    redirect_to :action => :show, :id => picture.id