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.
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:
That’s it! That’s all that’s needed to add extra quality and processing functionality to carrierwave.