What is Image Optimization?
As mentioned in a previous post, image optimization is finding the balance between an acceptable level of quality while having the smallest file size to support that quality. Large images slow down your web pages and when you combine slow load times with high traffic web pages, the user experience becomes poor. We can optimize images by using either a plugin or script, which in turn speeds up the load time of the page. Lossy and lossless compression are two methods commonly used. Optimizing images is the quickest way to see a performance increase on your web pages.
Correct file format
Your specific situation will determine which file format is best for you.
- PNG - higher quality image and larger file size
- JPEG - good balance of quality and file size
- GIF - best choice for animated images
- SVG - works great for logos, icons, text, and simple images and usually smaller in file size
How to optimize your images in Sitecore
In a perfect world, each Content Author/Editor would optimize every image they upload into Sitecore, but that will never be the case. So, we can implement some code to insure that every image on our site becomes optimized. There are many ways to implement a solution to handle optimizing images, but there are two I want to briefly discuss.
Option 1 - Extend the publishItem pipeline
The first option we can use is to create a new processor in the publishItem pipeline. You can use third party tools to handle the image compression like jpegtran, pngcrush, gifsicle or any other tools since there are many. The first step is to create a config patch file in your app_config/include folder. Then, create your processor, which will extend the PublishItemProcessor class, and point your new processor to a helper class you will create for optimizing the image. Check your image type and execute the appropriate third party optimizer. To save some processing power when items are published in the future, you can add a checkbox to the image item. If the item gets optimized, update the value of the field to true to show that it has been optimized and does not need to run through this process in the future.
Option 2 - Use Dianoga when an image is requested for the first time on the server
By using Dianoga, images are reduced in size, but not quality, when the image is first saved into the Media Cache. You can install Dianoga through Nuget. There is a separate npm package if you need svg optimization.
By using one of the two options above, the need to worry about image optimization is no longer an issue. So, after the code is implemented, your images will be optimized during the next publish or when the page loads and the server requests that image for the first time.