Last active
January 1, 2016 18:59
-
-
Save benerdin/8187081 to your computer and use it in GitHub Desktop.
Download and resize an image to a Bitmap using the ImageResizer nuget package. The resulting Bitmap is copied to a MemoryStream and returned.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Make sure to wrap a using() around any calls to DownloadAndResizeStream: | |
| using (var stream = DownloadAndResizeStream(uri, 100, 100, true)) { | |
| // Do what you need to with "stream" here | |
| } | |
| */ | |
| private Stream DownloadAndResizeStream(Uri sourceImageUrl, int width, int height, bool crop) | |
| { | |
| try | |
| { | |
| // Download image to file system | |
| using (var wc = new System.Net.WebClient()) | |
| { | |
| // Read image as stream | |
| using (var imageStream = wc.OpenRead(sourceImageUrl)) | |
| { | |
| // Resize settings | |
| var resizeSettings = new ImageResizer.ResizeSettings | |
| { | |
| Scale = ImageResizer.ScaleMode.DownscaleOnly, | |
| Width = width, | |
| Height = height | |
| }; | |
| if (crop) resizeSettings.Mode = ImageResizer.FitMode.Crop; | |
| // Resize image | |
| using (var b = ImageResizer.ImageBuilder.Current.Build(imageStream, resizeSettings)) | |
| { | |
| // If image does not meet minimum requirements, discard it | |
| if (b == null || b.Width < width || b.Height < height) | |
| { | |
| return null; | |
| } | |
| // Save resized image | |
| var memoryStream = new MemoryStream(); | |
| b.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png); | |
| return memoryStream; | |
| } | |
| } | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.ErrorException(ex.ToString(), ex); | |
| return null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment