Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Obtain original image from input stream
- using (var sourceImage = new Bitmap(Image.FromStream(inStream)))
- {
- //Thumbnail size and quality that may be saved in app settings or an environment variable
- int thumbSize = 150;
- int thumbQuality = 75;
- //Obtain source dimensions and initialize scaled dimensions and crop offsets
- float sourceWidth = sourceImage.Width;
- float sourceHeight = sourceImage.Height;
- float scaledSourceWidth = thumbSize;
- float scaledSourceHeight = thumbSize;
- float offsetWidth = 0;
- float offsetHeight = 0;
- //Calculate cropping offset
- if (sourceWidth > sourceHeight)
- {
- offsetWidth = (sourceWidth - sourceHeight) / 2;
- scaledSourceWidth = (sourceWidth / sourceHeight) * thumbSize;
- }
- else if (sourceHeight > sourceWidth)
- {
- offsetHeight = (sourceHeight - sourceWidth) / 2;
- scaledSourceHeight = (sourceHeight / sourceWidth) * thumbSize;
- }
- //Create new thumbnail image of height and width defined in thumbSize
- Bitmap thumbnail = new Bitmap((int)thumbSize, (int)thumbSize, sourceImage.PixelFormat);
- thumbnail.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
- using (var graphics = Graphics.FromImage(thumbnail))
- {
- //Draw source image scaled down with aspect ratio maintained onto the thumbnail with the offset
- graphics.CompositingQuality = CompositingQuality.HighSpeed;
- graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- graphics.CompositingMode = CompositingMode.SourceCopy;
- graphics.DrawImage(sourceImage, new Rectangle(0, 0, (int)scaledSourceWidth, (int)scaledSourceHeight), offsetWidth, offsetHeight, sourceWidth, sourceHeight, GraphicsUnit.Pixel);
- //Push thumbnail onto stream for upload
- using (MemoryStream stream = new MemoryStream())
- {
- var encoderParameters = new EncoderParameters(1);
- encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, Convert.ToInt64(thumbQuality));
- var codecInfo = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
- thumbnail.Save(stream, codecInfo, encoderParameters);
- stream.Position = 0;
- //Upload thumbnail to storage or download as an image file
- }
- }
- }
Add Comment
Please, Sign In to add comment