Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

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

Upvotes: 1

Views: 3057

Answers (1)

Diego Somar
Diego Somar

Reputation: 951

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.

Upvotes: 3

Related Questions