About the author

Miron Abramson
Me
Software Engineer,
CTO at PixeliT
and .NET addicted for long time.
Open source projects:
MbCompression - Compression library

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2014

Creative Commons License

Blog Flux Directory
Technology Blogs - Blog Top Sites

Resize images 'on the fly' while uploading

Lot of sites (specialy in the web 2.0 times) allows the user to upload images to the site. To save disk space and for visual design reasons, it is better to have the images is small size and specified dimensions. This can be made in two ways. One way is to tell the users to resize the images before uploading them, and the more 'User friendly' way is to let the user upload images with any size and dimensios, and resize them while the uploading.

Here is the code how can it be done:

First we define enum with the resize options:

 public enum ResizeOptions
{
    // Use fixed width & height without keeping the proportions
    ExactWidthAndHeight,

    // Use maximum width (as defined) and keeping the proportions
    MaxWidth,

    // Use maximum height (as defined) and keeping the proportions
    MaxHeight,

    // Use maximum width or height (the biggest) and keeping the proportions
    MaxWidthAndHeight
}

Second, the 'resize' method:

 public static System.Drawing.Bitmap DoResize(System.Drawing.Bitmap originalImg, int widthInPixels, int heightInPixels)
{
       System.Drawing.Bitmap bitmap;
       try
       {
           bitmap = new System.Drawing.Bitmap(widthInPixels, heightInPixels);
           using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap))
           {
               // Quality properties
               graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
               graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
               graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
               graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

               graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
               return bitmap;
           }
       }
       finally
       {
           if (originalImg != null)
           {
               originalImg.Dispose();
           }
       }
}

Third, the method that calculate the dimensions according to the enum value that passed:

 public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions)
{
    float f_width;
    float f_height;
    float dim;
    switch (resizeOptions)
    {
        case ResizeOptions.ExactWidthAndHeight:
            return DoResize(image, width, height);

        case ResizeOptions.MaxHeight:
            f_width = image.Width;
            f_height = image.Height;

            if (f_height <= height)
                return DoResize(image, (int)f_width, (int)f_height);

            dim = f_width / f_height;
            width = (int)((float)(height) * dim);
            return DoResize(image, width, height);

        case ResizeOptions.MaxWidth:
            f_width = image.Width;
            f_height = image.Height;

            if (f_width <= width)
                return DoResize(image, (int)f_width, (int)f_height);

            dim = f_width / f_height;
            height = (int)((float)(width) / dim);
            return DoResize(image, width, height);

        case ResizeOptions.MaxWidthAndHeight:
            int tmpHeight = height;
            int tmpWidth = width;
            f_width = image.Width;
            f_height = image.Height;

            if (f_width <= width && f_height <= height)
                return DoResize(image, (int)f_width, (int)f_height);

            dim = f_width / f_height;

            // Check if the width is ok
            if (f_width < width)
                width = (int)f_width;
            height = (int)((float)(width) / dim);
            // The width is too width
            if (height > tmpHeight)
            {
                if (f_height < tmpHeight)
                    height = (int)f_height;
                else
                    height = tmpHeight;
                width = (int)((float)(height) * dim);
            }
            return DoResize(image, width, height);
        default:
            return image;
    }
}

Last thing is to connect it all to the uploading event: (Our uploading control called 'fuPhoto' (Normal 'FileUpload' control))

 public bool UploadFile()
{
    // Make some validatins check (control have file or extension check...)

    int width = 300;
    int height = 300;

    // Do the resize, and save the file with desired name
    using( System.Drawing.Bitmap img = ResizeImage(new System.Drawing.Bitmap(fuPhoto.PostedFile.InputStream), width, height, ResizeOptions.MaxWidthAndHeight))
    {
        string destination = Server.MapPath("~") + Path.GetFileName(FileUpload1.FileName);
        switch (Path.GetExtension(fuPhoto.FileName).ToLower())
        {
            case ".gif":
                img.Save(destination, System.Drawing.Imaging.ImageFormat.Gif);
                break;
            case ".jpg":
            default:
                img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);
                break;
        }
    }
}

Update:

Some readers asked my about how can this code be used to resize the uploaded image and than save it in to the DB and not to the disk. To save the image to the DB we need to convert it into byte[] (That is how it needs to be sent to the Store Procedre). This can be done in some way. one way is:

 public static byte[] ImageToArray(Bitmap image, ImageFormat format)
 {
       using(MemoryStream mem = new MemoryStream())
       {
           mem.Position = 0;
           image.Save(mem, format);
           return mem.ToArray();
       }
  }

 Upload the file using the method 'ResizeImage', than convert the returned Bitmap into byte[] using this method, and send it to your Store Procedure.

done 

Currently rated 4.5 by 15 people

  • Currently 4.466667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | C#
Posted by Miron on Sunday, October 28, 2007 1:24 AM
Permalink | Comments (29) | Post RSSRSS comment feed

Related posts

Comments

DotNetKicks.com

Sunday, October 28, 2007 2:10 AM

trackback

Trackback from DotNetKicks.com

Resize images 'on the fly' while uploading

Josh Stodola us

Sunday, October 28, 2007 2:52 PM

Josh Stodola

That is funny becuase I planned to blog about an extremely similiar solution tomorrow! No need for me to do it now!

Best regards...

Aushi in

Thursday, December 13, 2007 5:58 PM

Aushi

Hello Miron,
i am using the same above code, me facing problem in executing it as i am getting the error

"Parameter is not valid."
Exception Details: System.ArgumentException: Parameter is not valid.

img.Save(FileUpload1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg );

i am at beginner ' s level..so could u plz help me in gettin out from this prob
Thx

Miron il

Sunday, December 16, 2007 10:28 PM

Miron

Hi Aushi,
Was a small bug in my code.
The code was updated and now working perfect.

Aushi in

Monday, December 17, 2007 4:38 PM

Aushi

Hello Miron

Thanku Great the code is perfect now. I am really greatfull to you.

Thanks

naveen in

Sunday, December 23, 2007 4:53 PM

naveen

Hi,
i am uploading the image as parameter of sqlserver stored procedure


before resize i fallowed the my way,
like

cmd.Parameters.Add("@picture", SqlDbType.Image, pic.Length).Value =
(byte[] pic = new byte[FileUpload1.PostedFile.filelenght];

this works fine with out resize.

if i used your code to resize the image,
how can i use your code like "public bool UploadFile()"
to pass parameter for my stored procedure

i tried diff ways some times its asking retrun type for bool,
can give me some idea about this

Miron us

Sunday, December 23, 2007 10:54 PM

Miron

Hi naveen,
See the updated post.

Aushi in

Monday, January 14, 2008 3:39 PM

Aushi

Hello miron

I stuck once again, actually now i would like to make the DLL of this code and would like to call it in my page...can u plz guide me as i am new to this...

Thanks

Miron us

Monday, January 14, 2008 9:30 PM

Miron

Aushi, What do you need?
I can't help you if I have no idea what r u trying to do...

Aushi in

Tuesday, January 15, 2008 8:03 PM

Aushi

hi Miron

Thanks, actually i got the solution myself. What i was doing instead of pasting the code, I was trying to make the DLL of the code and calling that DLL on the click event of the button to upload the image.The problem i was facing while making the DLL is that by default the " system.drawing" namespace is not available, for that we have to add the refrence for that.I hope that now its clear what i was trying to do..
Thanks

Mike us

Saturday, February 16, 2008 5:29 AM

Mike

Is there an example on how to user this class? I know you have to convert the uploaded file to a bitmap but I am unsure of how to do that. Any help would be great.

Thanks
Mike

Miron us

Saturday, February 16, 2008 5:49 AM

Miron

Hi Mike,
It's all there in the code in the post.
Look the method 'UploadFile()', The call to ResizeImage(new System.Drawing.Bitmap(fuPhoto.PostedFile.InputStream), width, height, ResizeOptions.MaxWidthAndHeight) convert the posted file stream into Bitmap.

Don us

Saturday, February 23, 2008 12:46 PM

Don

Miron,
Great work! I have been implementing a similar approach for two days. I stumbled onto your site trying to resolve an error with my approach that didn't make sense. I read your blog and felt your approach was way better and more flexible then what I was implementing. I implemented and it is working great. Thanks a million!
Don

Mike us

Monday, February 25, 2008 1:36 AM

Mike

Anyway to keep the transparentcies on gifs?

A us

Tuesday, April 01, 2008 5:16 PM

A

I think the code for converting the image to byte array is not fine, because I didnt see the parameter
(Bitmap image) in the implementation of the method (ImageToArray).


Can you check it and replay

Miron il

Wednesday, April 02, 2008 1:10 PM

Miron

@A
It's just there.
See the line: image.Save(mem, format);

Syed Shariq ae

Thursday, May 01, 2008 10:42 AM

Syed Shariq

I am some confusing in code I use ASP.NET 2.0 it give error in two places "path.GetFileName" & "Path.GetExtension:. The main thing which is confusing me very much is that if I use this code in my site and upload on a web server. After this in a browser I open my site, browse an image file from my pc and upload it, then it will upload the file on the web server where my site reside or not, because to see this "img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);" it seem it only save image on the local disk and not the web server. File Upload control use for file upload but here it is use only get file and then resize it.

Miron il

Saturday, May 03, 2008 12:11 PM

Miron

@Syed,
You are a little mixed up. All the code is running on the server only. It uses the "Upload control" to get the file stream from the client and process it on the server side, resize it and save it - all on the server.
If you use an asp.net FileUpload control and use the 'browse' button to select a file, you don't have to get any exception.
Make sure you validate (in the server side) that the control have a file, and the extension is gif or jpg.

Syed Shariq ae

Sunday, May 04, 2008 7:23 AM

Syed Shariq

Thanks for your comment, it really solve my problem. Again thanks. I have one other question which I hope you give answer, but it is not related with this title. An class/dll which is provide data accees and other functionality from Oracle and for this purpose use RDO, can I use this class/dll in ASP.NET. thanks IN ADVANCE.

Syed Shariq ae

Sunday, May 04, 2008 7:26 AM

Syed Shariq

Thanks for your comment, it really solve my problem. Again thanks. I have one other question which I hope you give answer, but it is not related with this title. An class/dll which is provide data accees and other functionality from Oracle and for this purpose use RDO, can I use this class/dll in ASP.NET. VERY THANKS IN ADVANCE.

Francesco it

Sunday, May 11, 2008 9:06 AM

Francesco

Great piece of code! And easy to implement too!
Thanks.

cesar suarez co

Monday, June 23, 2008 3:43 AM

cesar suarez

Hey an amazing code and easy to implement, thanks a lot

moshe il

Monday, July 28, 2008 4:06 PM

moshe

האם ניתן לבצע את הקוד הזה גם ב -ASP הרגיל ולא ב ASP.NET ?
כמו כן השתמשתי ב-UPLOAD חינם ללא COMPONNET .
אני יודע שאני פרימיטיבי אך אנא ענה לי !!!

BT us

Monday, August 04, 2008 9:08 AM

BT

I received a GDI+ generic error when I attempted to resize an image with same source as destination: http://support.microsoft.com/?id=814675

The article is very useful. Thx

achieef tr

Sunday, September 21, 2008 6:16 PM

achieef

Thank you very much. that is absolutely what ı was looking for.

Addy in

Sunday, December 07, 2008 8:13 PM

Addy

Hi, Friendz,
Your Code is cool One, I also Develop Similer Code, I also used your code,
but I found One problem, Code not provide Good quality GIF its provide blur and fade GIF
My code is also gives same problem with GIF Format
If you Found any Solution of theis Problem please Just Mail Me
Thank you

Greate Efforts
Regards
Addy Parmar

jignesh in

Monday, December 22, 2008 9:04 PM

jignesh

Hi,Miron
Your code is really cool.I used it in my web project.

Thanks
Jignesh

achim ph

Thursday, April 23, 2009 3:22 PM

achim

awesome! Just did a lil tweak to the code to fit my needs and done! Thanks man for sharing! owe this one to you.
great work! :p

Ted Porter gb

Thursday, November 19, 2009 12:48 AM

Ted Porter

Hi Miron,

You cannot believe how many hours (maybe days) of coding you have just saved me - Simply Brilliant!

Thank You,


Ted.