Resize Image in ASP.NET C#

10. December 2008

So I created this classed based off of a couple of other posts I read.  I have listed those references.  The reason I like this is because when users are uploading pics they may not resize them on their own so they may be uploading a 1MB pic file they just copied off their camera.  So this post will be a bit long because of the code but just bare with me.  I'll paste the class for the image resize and then the code behind for the test page.  The UI for the test page is just a file upload control and button. I modified this to have a seperate function to save the image

So here is the class for doing the image resize:
Note I copied the whole thing so you may need to change the namespace.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

namespace TestWeb
{
    /// <summary>
    /// class inspired by the following references:
    /// http://www.eggheadcafe.com/articles/20030515.asp
    /// http://forums.asp.net/t/1038068.aspx
    /// </summary>
    public class imageResize
    {
        public static byte[] ResizeFromByteArray(int MaxSideSize, Byte[] byteArrayIn, string fileName)
        {
            byte[] byteArray = null;  // really make this an error gif
            MemoryStream ms = new MemoryStream(byteArrayIn);
            byteArray = imageResize.ResizeFromStream(MaxSideSize, ms, fileName);

            return byteArray;
        }
       
        /// <summary>
        /// converts stream to bytearray for resized image
        /// </summary>
        /// <param name="MaxSideSize"></param>
        /// <param name="Buffer"></param>
        /// <returns></returns>
        public static byte[] ResizeFromStream(int MaxSideSize, Stream Buffer, string fileName)
        {
            byte[] byteArray = null;  // really make this an error gif

            try
            {

                Bitmap bitMap = new Bitmap(Buffer);
                int intOldWidth = bitMap.Width;
                int intOldHeight = bitMap.Height;

                int intNewWidth;
                int intNewHeight;

                int intMaxSide;

                if (intOldWidth >= intOldHeight)
                {
                    intMaxSide = intOldWidth;
                }
                else
                {
                    intMaxSide = intOldHeight;
                }

                if (intMaxSide > MaxSideSize)
                {
                    //set new width and height
                    double dblCoef = MaxSideSize / (double)intMaxSide;
                    intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                    intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
                }
                else
                {
                    intNewWidth = intOldWidth;
                    intNewHeight = intOldHeight;
                }

                Size ThumbNailSize = new Size(intNewWidth, intNewHeight);
                System.Drawing.Image oImg = System.Drawing.Image.FromStream(Buffer);
                System.Drawing.Image oThumbNail = new Bitmap (ThumbNailSize.Width, ThumbNailSize.Height);
               
                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle oRectangle = new Rectangle
                    (0, 0, ThumbNailSize.Width, ThumbNailSize.Height);

                oGraphic.DrawImage(oImg, oRectangle);

                MemoryStream ms = new MemoryStream();
                oThumbNail.Save(ms, ImageFormat.Jpeg);
                byteArray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));

                oGraphic.Dispose();
                oImg.Dispose();
                ms.Close();
                ms.Dispose();
            }
            catch (Exception)
            {
                int newSize = MaxSideSize - 20;
                Bitmap bitMap = new Bitmap(newSize, newSize);
                Graphics g = Graphics.FromImage(bitMap);
                g.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(0, 0, newSize, newSize));

                Font font = new Font("Courier", 8);
                SolidBrush solidBrush = new SolidBrush(Color.Red);
                g.DrawString("Failed File", font, solidBrush, 10, 5);
                g.DrawString(fileName, font, solidBrush, 10, 50);

                MemoryStream ms = new MemoryStream();
                bitMap.Save(ms, ImageFormat.Jpeg);
                byteArray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));

                ms.Close();
                ms.Dispose();
                bitMap.Dispose();
                solidBrush.Dispose();
                g.Dispose();
                font.Dispose();

            }
            return byteArray;
        }

        /// <summary>
        /// Saves the resized image to specified file name and path as JPEG
        /// and also returns the bytearray for any other use you may need it for
        /// </summary>
        /// <param name="MaxSideSize"></param>
        /// <param name="Buffer"></param>
        /// <param name="fileName">No Extension</param>
        /// <param name="filePath">Examples: "images/dir1/dir2" or "images" or "images/dir1"</param>
        /// <returns></returns>
        public static byte[] SaveFromStream(int MaxSideSize, Stream Buffer, string fileName, string filePath)
        {
            byte[] byteArray = null;  // really make this an error gif

            try
            {

                Bitmap bitMap = new Bitmap(Buffer);
                int intOldWidth = bitMap.Width;
                int intOldHeight = bitMap.Height;

                int intNewWidth;
                int intNewHeight;

                int intMaxSide;

                if (intOldWidth >= intOldHeight)
                {
                    intMaxSide = intOldWidth;
                }
                else
                {
                    intMaxSide = intOldHeight;
                }

                if (intMaxSide > MaxSideSize)
                {
                    //set new width and height
                    double dblCoef = MaxSideSize / (double)intMaxSide;
                    intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                    intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
                }
                else
                {
                    intNewWidth = intOldWidth;
                    intNewHeight = intOldHeight;
                }

                Size ThumbNailSize = new Size(intNewWidth, intNewHeight);
                System.Drawing.Image oImg = System.Drawing.Image.FromStream(Buffer);
                System.Drawing.Image oThumbNail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);

                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle oRectangle = new Rectangle
                    (0, 0, ThumbNailSize.Width, ThumbNailSize.Height);

                oGraphic.DrawImage(oImg, oRectangle);

                //Save File
                string newFileName = string.Format(System.Web.HttpContext.Current.Server.MapPath("~/{0}/{1}.jpg"), filePath, fileName);
                oThumbNail.Save(newFileName, ImageFormat.Jpeg);

                MemoryStream ms = new MemoryStream();
                oThumbNail.Save(ms, ImageFormat.Jpeg);
                byteArray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));

                oGraphic.Dispose();
                oImg.Dispose();
                ms.Close();
                ms.Dispose();
            }
            catch (Exception)
            {
                int newSize = MaxSideSize - 20;
                Bitmap bitMap = new Bitmap(newSize, newSize);
                Graphics g = Graphics.FromImage(bitMap);
                g.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(0, 0, newSize, newSize));

                Font font = new Font("Courier", 8);
                SolidBrush solidBrush = new SolidBrush(Color.Red);
                g.DrawString("Failed To Save File or Failed File", font, solidBrush, 10, 5);
                g.DrawString(fileName, font, solidBrush, 10, 50);

                MemoryStream ms = new MemoryStream();
                bitMap.Save(ms, ImageFormat.Jpeg);
                byteArray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));

                ms.Close();
                ms.Dispose();
                bitMap.Dispose();
                solidBrush.Dispose();
                g.Dispose();
                font.Dispose();

            }
            return byteArray;
        }
    }
}

Here is the code behind for the test page if you want to test it out:

protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            byte[] imgNew;
            imgNew = imageResize.ResizeFromStream(400, FileUpload1.PostedFile.InputStream, FileUpload1.PostedFile.FileName);

            Response.BinaryWrite(imgNew);

            byte[] imgNewSave;
            imgNewSave = imageResize.SaveFromStream(400, FileUpload1.PostedFile.InputStream, "newPicFromResize", "images");

        }

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

ASP.NET

Comments

frank
1/8/2009 5:14:45 PM #
Thank you! Works like a charm.
3/23/2009 2:39:28 AM #
I wanted to personally thank you! I pulled out my remaining hair trying to resize my Byte[]!! This worked great! Thanks again!
Jevgenij
4/2/2009 9:38:23 PM #
Many thanks for posting this code. It helped me a lot! Smile
Harvinder Singh
6/17/2009 8:21:42 AM #
thanks you verrry verry much for this code
Justin
7/9/2009 12:37:59 AM #
Thanks a lot. It is really helpful!
Ali
8/15/2009 3:23:30 AM #
Thank you it is a great work. It runs fine and display the image correctly, But I got exception when I try to save to disk at statement:

oThumbNail.Save(newFileName, ImageFormat.Jpeg);

I am sure I am missing something here. Any assistant will grealty be appreciated.

A.
Tran Thanh Dan
10/20/2009 5:03:20 PM #
It's great! Thanks for your code.
senthilkumart
11/18/2009 11:57:06 AM #
Thanks a lot to you people!!!!!!!!!!! Great job. Good opportunity to learn more from you...
Veon
2/17/2010 10:32:48 AM #
Thanks. Wonderful. =)

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading