/// <summary> /// Resizes an image to given size. The resized image will be saved to the given stream. Images that /// are smaller than the requested target size will not be scaled up, but returned in original size. /// </summary> /// <param name="originalStream">Image to resize</param> /// <param name="maxWidth">Maximum image width</param> /// <param name="maxHeight">Maximum image height</param> /// <param name="mediaType">MediaType</param> /// <param name="fanArtType">FanArtType</param> /// <param name="fanArtName">Fanart name</param> /// <param name="originalFile">Original Filename</param> /// <returns></returns> protected static Stream ResizeImage(Stream originalStream, int maxWidth, int maxHeight, string originalFile) { if (maxWidth == 0 || maxHeight == 0) { return(originalStream); } try { if (!Directory.Exists(CACHE_PATH)) { Directory.CreateDirectory(CACHE_PATH); } int maxSize = GetBestSupportedSize(maxWidth, maxHeight); //Don't include the extension here, we support both jpg and png files, the CachedImageExists method will check with all supported extensions string thumbFilenameWithoutExtension = Path.Combine(CACHE_PATH, string.Format("{0}x{1}_{2}", maxSize, maxSize, GetCrc32(originalFile))); string cachedFilenameWithExtension; if (CachedImageExists(thumbFilenameWithoutExtension, out cachedFilenameWithExtension)) { using (originalStream) return(new FileStream(cachedFilenameWithExtension, FileMode.Open, FileAccess.Read)); } Image fullsizeImage = Image.FromStream(originalStream); //Image doesn't need resizing, just return the original if (fullsizeImage.Width <= maxSize && fullsizeImage.Height <= maxSize) { fullsizeImage.Dispose(); originalStream.Position = 0; return(originalStream); } //Check whether the image has an alpha channel to determine whether to save it as a png or jpg //Must be done before resizing as resizing disposes the fullsizeImage bool isAlphaPixelFormat = Image.IsAlphaPixelFormat(fullsizeImage.PixelFormat); MemoryStream resizedStream = new MemoryStream(); using (originalStream) using (fullsizeImage) using (Image newImage = ImageUtilities.ResizeImage(fullsizeImage, maxSize, maxSize)) { if (isAlphaPixelFormat) { //Image supports an alpha channel, save as a png and add the appropriate extension ImageUtilities.SavePng(thumbFilenameWithoutExtension + ".png", newImage); ImageUtilities.SavePng(resizedStream, newImage); } else { //No alpha channel, save as a jpg and add the appropriate extension ImageUtilities.SaveJpeg(thumbFilenameWithoutExtension + ".jpg", newImage, 95); ImageUtilities.SaveJpeg(resizedStream, newImage, 95); } } resizedStream.Position = 0; return(resizedStream); } catch (Exception) { return(originalStream); } }