Exemplo n.º 1
0
        private ResizedImage GetResizedImage(Image image, int proposedWidth, int proposedHeight)
        {
            ResizedImage retVal;

            int newWidth;
            int newHeight;
            //TODO: the max_height, max_width needs to be more flexible - write unit test around it too
            if (image.Width < proposedWidth && image.Height < proposedHeight)
            {
                //image was smaller than proposed dimensions - use original

                newWidth = image.Width;
                newHeight = image.Height;
            }
            else
            {
                //image was larger than proposed dimensions - resize it

                decimal diffRatio;

                if (image.Width > image.Height)
                {
                    diffRatio = (decimal)proposedWidth / image.Width;
                    newWidth = proposedWidth;
                    decimal tempHeight = image.Height * diffRatio;
                    newHeight = (int)tempHeight;
                }
                else
                {
                    diffRatio = (decimal)proposedHeight / image.Height;
                    newHeight = proposedHeight;
                    decimal tempWidth = image.Width * diffRatio;
                    newWidth = (int)tempWidth;
                }
            }

            using (var resizedBitmap = new Bitmap(newWidth, newHeight))
            {
                using (Graphics newGraphic = Graphics.FromImage(resizedBitmap))
                {
                    retVal = new ResizedImage { Image = new MemoryStream(), Width = newWidth, Height = newHeight };
                    using (var encoderParameters = new EncoderParameters(1))
                    {
                        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L);

                        newGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        newGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        newGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        newGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                        newGraphic.DrawImage(image, 0, 0, newWidth, newHeight);
                        resizedBitmap.Save(retVal.Image, GetImageCodec(image.RawFormat), encoderParameters);

                        //Stream is NOT disposed here - it is sent back as an open stream
                        retVal.Image.Position = 0;
                    }
                }
            }

            return retVal;
        }
Exemplo n.º 2
0
 private void DisposeImageIfNotEmpty(ResizedImage resizedImage, IList<Exception> exceptions)
 {
     if (resizedImage != null)
     {
         try
         {
             resizedImage.Image.Dispose();
         }
         catch (Exception ex)
         {
             exceptions.Add(ex);
         }
     }
 }