public byte[] Create(Stream source, ImageSize desiredSize, string contentType) { using (var image = Image.FromStream(source)) { var originalSize = new ImageSize { Height = image.Height, Width = image.Width }; var size = resizer.Resize(originalSize, desiredSize); using (var thumbnail = new Bitmap(size.Width, size.Height)) { ScaleImage(image, thumbnail); using (var memoryStream = new MemoryStream()) { thumbnail.Save(memoryStream, ImageFormats[contentType]); return memoryStream.ToArray(); } } } }
public ImageSize Resize(ImageSize originalSize, ImageSize targetSize) { var aspectRatio = (float)originalSize.Width / (float)originalSize.Height; var width = targetSize.Width; var height = targetSize.Height; if (originalSize.Width > targetSize.Width || originalSize.Height > targetSize.Height) { if (aspectRatio > 1) { height = (int)(targetSize.Height / aspectRatio); } else { width = (int)(targetSize.Width * aspectRatio); } } else { width = originalSize.Width; height = originalSize.Height; } return new ImageSize { Width = Math.Max(width, 1), Height = Math.Max(height, 1) }; }
private FileContentResult CreateThumbnail(string physicalPath) { using (var fileStream = System.IO.File.OpenRead(physicalPath)) { var desiredSize = new ImageSize { Width = ThumbnailWidth, Height = ThumbnailHeight }; const string contentType = "image/png"; return File(thumbnailCreator.Create(fileStream, desiredSize, contentType), contentType); } }