Search code examples
rubyruby-on-rails-4rmagick

How to use rmagick in Rails?


I am a new bee in Ruby on Rails. I want to do image manipulation in my rails project using rmagick. But am am confused how to do it. I have practiced 'rmagick' on console. But now i want to manipulate an uploaded image in my rails project using rmagick. help me in this??


Solution

  • You are probably better of using Carrierwave or PaperClip gem unless you plan to do something really exotic.

    Essentially these 2 use imagemagic in the background, but have automated the common actions like image uploading, resizing and avaratar user pics.

    As added bonus unlike rmagic gem they come with good documentation to get started.

    Here you go.

    1. PaperClip https://github.com/thoughtbot/paperclip
    2. CarrierWave https://github.com/carrierwaveuploader/carrierwave

    That said if you want to use Rmagic here is an example of image resizing controller method.

    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