如何在 Rails 中使用 rmagick?

Vai*_*put 1 ruby rmagick ruby-on-rails-4

我是 Ruby on Rails 的新人。我想使用 rmagick 在我的 Rails 项目中进行图像处理。但我很困惑如何去做。我在控制台上练习过“rmagick”。但现在我想使用 rmagick 在我的 Rails 项目中操作上传的图像。帮我这个?

Kim*_*kka 5

除非您打算做一些非常奇特的事情,否则您可能更适合使用 Carrierwave 或 PaperClip gem。

本质上,这两个在后台使用 imagemagic,但自动执行常见操作,例如图像上传、调整大小和头像用户图片。

与 rmagic gem 不同的是,它们附带了良好的入门文档,这是额外的好处。

干得好。

  1. 回形针https://github.com/thoughtbot/paperclip
  2. CarrierWave https://github.com/rierwaveuploader/carrierwave

也就是说,如果您想使用 Rmagic,这里是图像调整大小控制器方法的示例。

def resize_images
    require 'rubygems'
    require 'RMagick'
    include Magick
    require "open-uri"

    file_url = open('URL to image')
    save_path = "/"

    f = File.new( File.join(save_path, file_url), "wb")
    f.write file_url.read 
    f.close

    image = Magick::Image.read(file_url).first
    image.change_geometry!("1500x150") { |cols, rows, img|
        newimg = img.resize(cols, rows)
        newimg.write("newfilename.jpg")
    }
end
Run Code Online (Sandbox Code Playgroud)