CarrierWave is a great gem for adding image uploading and basic processing abilities to your Rails applications. By default there is no way to set the quality of the resized images, which could be a very useful feature.

One of the applications that we’re currently building has a requirement to resize and compress images to produce smaller file sizes, as well as stripping out any personal information that may be stored in the uploaded images.

Out of the box CarrierWave provides a consistent interface to process images using RMagick, MiniMagick or ImageScience. Resizing and cropping is supported for all three image processing engines but setting the quality or removing personal data is not supported. Thankfully, CarrierWave provides an easy way to extend the default functionality so we can do more.

For the examples I’ll be adding extra functionality to RMagick processing. If you’re using MiniMagick or ImageScience the methods will need to be altered to work correctly. We’ll start by adding a new initializer into our application.

# config/initializers/carrierwave_initializer.rb

module CarrierWave
  module RMagick

    # Rotates the image based on the EXIF Orientation
    def fix_exif_rotation
      manipulate! do |img|
        img.auto_orient!
        img = yield(img) if block_given?
        img
      end
    end

    # Strips out all embedded information from the image
    def strip
      manipulate! do |img|
        img.strip!
        img = yield(img) if block_given?
        img
      end
    end

    # Reduces the quality of the image to the percentage given
    def quality(percentage)
      manipulate! do |img|
        img.write(current_path){ self.quality = percentage }
        img = yield(img) if block_given?
        img
      end
    end

  end
end

You may be wondering about the fix_exif_rotation method. Well, some modern cameras always take photos upright, in portrait. When you take a photo in landscape mode the photo is actually saved as a portrait, but the photo will contain some extra orientation metadata. When we remove the embedded data in the photo this value gets removed, so as a result we need to manually rotate the photo, which is what this method does.

The application server will need to be restarted before the new initializer can be used. Once restarted the new filters can be used in an uploader like so:

# app/uploaders/avatar_uploader.rb

process :fix_exif_rotation
process :strip
process :resize_to_fill => [1024, 768]
process :quality => 90 # Percentage from 0 - 100

That’s it! That’s all that’s needed to add extra quality and processing functionality to carrierwave.