In my current project, we are having a lot of images, that aren’t apart of the media library, but who still has to be resized and served to the browser. The project was started outside of Sitecore, and therefor had its own implementation of an image scaler. When that code failed, I thought it should be able to use Sitecores awesome image scaling function, on images not in the media library, and implement that. It turns out it’s quite easy to hook into the mechanism, by using only a few lines of code:
/// <summary> /// Scales an image using sitecores own image scaling mechanisme /// </summary> /// <param name="originalImagePath">Path to original image</param> /// <param name="scaledImagePath">Path to save the scaled image to</param> /// <param name="maxWidth">Max width param</param> /// <param name="maxHeight">Max height param</param> public static void GenerateScaledImageUsingSitecore(string originalImagePath, string scaledImagePath, int maxWidth, int maxHeight) { try { // Instinciate a ImageEffectResize object, this is the one that does the resizing var resizer = new ImageEffectsResize(); using (FileStream imageStream = File.OpenRead(originalImagePath)) { // Get the image type form config ImageFormat imageFormat = MediaManager.Config.GetImageFormat(Path.GetExtension(originalImagePath).Replace(".","")); // Initialize the TransformationOptions, giving params for the transformation var transformationOptions = new TransformationOptions() { AllowStretch = false, BackgroundColor = Color.White, IgnoreAspectRatio = false, MaxSize = new Size(maxWidth, maxHeight), Scale = 0, Size = new Size(0, 0) }; // do the resizing, and save image Stream resultStream = resizer.ResizeImageStream(imageStream, transformationOptions, imageFormat); string dir = Path.GetDirectoryName(scaledImagePath); if (dir != null && !Directory.Exists(dir)) Directory.CreateDirectory(dir); using (FileStream fileStream = File.Create(scaledImagePath)) { resultStream.CopyTo(fileStream); } } } catch (Exception ex) { // handle exception Log.Error(String.Format("Error while trying to resize image using Sitecore, original path: {0}, scaled maxsize: {1}x{2}", originalImagePath, maxWidth, maxHeight), ex, typeof(string)); } }
The code simply takes a path to the original media, a path to save the image, and a maxwith and maxheight.