How to: create a thumbnail with both color and grayscale versions in one image

jeroenhouben edited this page Jun 25, 2012 · 3 revisions
Clone this wiki locally

If you need both grayscale & color versions of an image (for CSS transitions or other tricks), you can put them in one file to save on browser requests.

The result will look something like this:

Result

class ThumbnailUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :fog

  process :resize_to_fill  => [50, 50]

  version :gray do
    process :convert_to_grayscale
  end

  version :merged do
    process :merge
  end

  def convert_to_grayscale
    manipulate! do |img|
      img.colorspace("Gray")
      img.brightness_contrast("-30x0")
      img = yield(img) if block_given?
      img
    end
  end

  def merge
    manipulate! do |img|
      img.combine_options do |cmd|
        cmd.gravity "north"
        cmd.extent "50x100"
      end

      img = img.composite(::MiniMagick::Image.open(model.thumbnail.gray.current_path, "jpg")) do |c|
        c.gravity "south"
      end
      img = yield(img) if block_given?
      img
    end
  end
end

Using RMagick you can use this bit of code:

class AvatarUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  
  version :small do
    process :resize_to_fill => [50, 50]
    version :sprite do
      process :make_sprite
    end
  end
  
  # Combine images to a sprite
  def make_sprite
    manipulate! do |img|
      list = Magick::ImageList.new
      list << img
      list << img.quantize(256, Magick::GRAYColorspace)
      img = list.append(true)
    end
  end
end