Saturday, February 13, 2010

Resize image and save without saving it to temporary file, C#

Upload an image after resizing to specific size without saving it to temporary file.      


ResizeImageAndSave(fileImage.PostedFile.InputStream, Width, Height, FileName);

        ///
        /// Resize image of Weight X Height and save
        ///

        public static void ResizeImageAndSave(Stream fs, int intW, int intH, string FileName)
        {
            System.Drawing.Image objImg = Bitmap.FromStream(fs);
            int intImgH = objImg.Height;
            int intImgW = objImg.Width;
            double R = ((double)intImgW / (double)intImgH);
            //if image is greater than 800*800
            if (intImgH > intImgW)
            {
                if (intImgH > intH)
                {
                    intImgH = intH;
                    intImgW = (int)(intH * R);
                }
            }
            else
            {
                if (intImgW > intW)
                {
                    intImgW = intW;
                    intImgH = (int)(intW / R);
                }
            }

          
            Bitmap outputImage = new Bitmap(intImgW, intImgH,PixelFormat.Format24bppRgb);
            outputImage.SetResolution(objImg.HorizontalResolution, objImg.VerticalResolution);
            Graphics graphics = Graphics.FromImage(outputImage);
            graphics.Clear(Color.White);
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(objImg, new Rectangle(0, 0, intImgW, intImgH), new Rectangle(4, 4, objImg.Width - 4, objImg.Height - 4), GraphicsUnit.Pixel);
            graphics.Dispose();
            outputImage.Save(FileName);
            outputImage.Dispose();
            outputImage = null;
        }

No comments: