Search code examples
ruby-on-railsrubyimagemagickcarrierwavermagick

How can I create thumbnail with carrierwave and a imagemagick script?


I'm using carrierwave to creating thumbnails, but I don't know how can -i use with this script.

mogrify -resize 246x246 -background none -gravity center -extent 246x246 -format png -quality 75 -path thumbs penguins.jpg

This script creating thumbnails and works good, but I would like to use this or similar in carrierwave versions.


Solution

  • The documentation on doing advanced configuration of image manipulation with carrierwave is here:

    https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Efficiently-converting-image-formats#full-example

    If you look at the def mogrify section, you see that in the img.format("png") do |c| block is where the image manipulation options are passed.

    That variable c is actually an instance of MiniMagick, which is a thin wrapper around mogrify.

    https://github.com/minimagick/minimagick/

    The full API for MiniMagick is not quite there, but if you dig into the source, you can find they have a list of all the possible methods they use here:

    https://github.com/minimagick/minimagick/blob/master/lib/mini_magick.rb#L39

    And those are all defined down below:

    https://github.com/minimagick/minimagick/blob/master/lib/mini_magick.rb#L456

    I would suggest adding the options you want to your own uploader:

     def mogrify(options = {})
        manipulate! do |img|
          img.format("png") do |c|
            # Add other options here:
    
            c.gravity     options[:gravity]
            c.background  options[:background]
            c.extend      options[:extend]
            c.quality     options[:quality]
    
            # Original options follow:
    
            c.fuzz        "3%"
            c.trim
            c.rotate      "#{options[:rotate]}" if options.has_key?(:rotate)
            c.resize      "#{options[:resolution]}>" if options.has_key?(:resolution)
            c.resize      "#{options[:resolution]}<" if options.has_key?(:resolution)
            c.push        '+profile'
            c.+           "!xmp,*"
            c.profile     "#{Rails.root}/lib/color_profiles/sRGB_v4_ICC_preference_displayclass.icc"
            c.colorspace  "sRGB"
          end
          img
        end
      end