Guest User

Untitled

a guest
Jun 24th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. //Obtain original image from input stream
  2. using (var sourceImage = new Bitmap(Image.FromStream(inStream)))
  3. {
  4. //Thumbnail size and quality that may be saved in app settings or an environment variable
  5. int thumbSize = 150;
  6. int thumbQuality = 75;
  7.  
  8. //Obtain source dimensions and initialize scaled dimensions and crop offsets
  9. float sourceWidth = sourceImage.Width;
  10. float sourceHeight = sourceImage.Height;
  11. float scaledSourceWidth = thumbSize;
  12. float scaledSourceHeight = thumbSize;
  13. float offsetWidth = 0;
  14. float offsetHeight = 0;
  15.  
  16. //Calculate cropping offset
  17. if (sourceWidth > sourceHeight)
  18. {
  19. offsetWidth = (sourceWidth - sourceHeight) / 2;
  20. scaledSourceWidth = (sourceWidth / sourceHeight) * thumbSize;
  21. }
  22. else if (sourceHeight > sourceWidth)
  23. {
  24. offsetHeight = (sourceHeight - sourceWidth) / 2;
  25. scaledSourceHeight = (sourceHeight / sourceWidth) * thumbSize;
  26. }
  27.  
  28. //Create new thumbnail image of height and width defined in thumbSize
  29. Bitmap thumbnail = new Bitmap((int)thumbSize, (int)thumbSize, sourceImage.PixelFormat);
  30. thumbnail.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
  31.  
  32. using (var graphics = Graphics.FromImage(thumbnail))
  33. {
  34. //Draw source image scaled down with aspect ratio maintained onto the thumbnail with the offset
  35. graphics.CompositingQuality = CompositingQuality.HighSpeed;
  36. graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
  37. graphics.CompositingMode = CompositingMode.SourceCopy;
  38. graphics.DrawImage(sourceImage, new Rectangle(0, 0, (int)scaledSourceWidth, (int)scaledSourceHeight), offsetWidth, offsetHeight, sourceWidth, sourceHeight, GraphicsUnit.Pixel);
  39.  
  40. //Push thumbnail onto stream for upload
  41. using (MemoryStream stream = new MemoryStream())
  42. {
  43. var encoderParameters = new EncoderParameters(1);
  44. encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, Convert.ToInt64(thumbQuality));
  45. var codecInfo = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
  46. thumbnail.Save(stream, codecInfo, encoderParameters);
  47. stream.Position = 0;
  48.  
  49. //Upload thumbnail to storage or download as an image file
  50. }
  51. }
  52. }
Add Comment
Please, Sign In to add comment