Search code examples
ruby-on-railsrubyimagemagickcarrierwaveminimagick

Optimize image using mini-magick and carrierwave in rails


I am using carrierwave for uploading image. Now I want to optimize images also. Like if user upload image of any size , I want to optimize that image in less 200kb size.

For that I add mini-magick gem. Here is my code

version :listing_main do
  image = ::MiniMagick::Image::read(File.binread(@file.file))
  // Want to compress image here      
  resize_to_fill 800,600
end

Issue is that how I can compress image , not find any way and tutorial for that


Solution

  • To change the image quality using Mini Magick and CarrierWave is simple.

    First, go to the file: config/initializers/carrierwave.rb. If not exists, create one. Put the code:

    module CarrierWave
        module MiniMagick
            def quality(percentage)
                manipulate! do |img|
                    img.quality(percentage.to_s)
                    img = yield(img) if block_given?
                    img
                end
            end
        end
    end
    

    After that, go to your image_uploader file. In my case, it is in app/uploaders/image_uploader.rb

    version :listing_main do    
        process resize_to_fill: [800, 600]
        process :quality => 70
    end
    

    I'm using exactly this code and it works fine.