Image Upload and Resize


Lets assume we have a FileUpload control (named fuImageFile) and a Button control (btnUpload) and we’re going to upload the image when we click our button. The simplest method of uploading our file might look something like this :

Listing – 1

    protected string savePath = "~/uploaded/";
    protected void btnUpload_Click(object sender, EventArgs e)
    {

        string fileName = fuImageFile.FileName;

        string saveName = Server.MapPath(savePath) + fileName;

        fuImage.SaveAs(saveName);

    }

So now we can upload an image to our server, what about resizing that image? For this to work you will need to add a using directive

Listing – 2

    using System.Drawing;
    using System.Drawing.Imaging;

Next,

we’ll look at how we go about resizing an image (in the form of a Bitmap object) and then at how to integrate that into our upload page.

Listing – 3

    public Bitmap ResizeBitmap (Bitmap src, int newWidth, int newHeight)
    {
        Bitmap result = new Bitmap(newWidth, newHeight);
        using ( Graphics g = Graphics.FromImage((System.Drawing.Image)result) )
        {
            g.DrawImage(src, 0, 0, newWidth, newHeight);
        }
        return result;
    }

This method takes a Bitmap object and two numbers specifying the height and width of the required image. We then create a new empty Bitmap at the desired size (result) , we then obtain a Graphics object from it (NB: the Graphics object remains associated with the Bitmap) and draw our source image into it.

When we return the result we have an Bitmap object with the image data we drew into the Graphics object.So now lets work it into our page

Listing – 4

    protected void btnUpload_Click (object sender, EventArgs e)
    {

        string fileName = fuImageFile.FileName;

        // Get the bitmap data from the uploaded file

        Bitmap src = Bitmap.FromStream(fuImageFile.PostedFile.InputStream) as Bitmap;

        // Resize the bitmap data

        Bitmap result = ResizeBitmap (src, 200, 200);

        string saveName = Server.MapPath(savePath) + fileName;

        result.Save(saveName, ImageFormat.Jpeg);

    }

What we do here is take the InputStream of the FileUpload’s PostedFile property and create a Bitmap with it, once we have this bitmap object we can call it’s Save method to save it to the local disk.

Proportional Resizing

The problem with this ResizeBitmap is that it will stretch and pull your input image to fit the dimensions supplied which 99% of the time is not what we will want. We usually want to scale an image keeping its proportions. Take a look at the ProportionallyResizeBitmap method below:

Listing – 5

    public Bitmap ProportionallyResizeBitmap (Bitmap src, int maxWidth, int maxHeight)
    {

        // original dimensions
        int w = src.Width;
        int h = src.Height;

        // Longest and shortest dimension
        int longestDimension = (w>h)?w: h;
        int shortestDimension = (w<h)?w: h;

        // propotionality
        float factor = ((float)longestDimension) / shortestDimension;

        // default width is greater than height
        double newWidth = maxWidth;
        double newHeight = maxWidth/factor;

        // if height greater than width recalculate
        if ( w < h )
        {
            newWidth = maxHeight / factor;
            newHeight = maxHeight;
        }

        // Create new Bitmap at new dimensions
        Bitmap result = new Bitmap((int)newWidth, (int)newHeight);
        using ( Graphics g = Graphics.FromImage((System.Drawing.Image)result) )
        g.DrawImage(src, 0, 0, (int)newWidth, (int)newHeight);

        return result;
    }

This method takes a maxWidth and a maxHeight instead of a newWidth and newHeight, it then does a bit of maths to figure out which is the longest, the original height or the original width, works out the ratio of these two numbers and applies them appropriatley to the target size and resizes the image accordingly.

See the Microsoft Knowledge Base article http://support.microsoft.com/?id=814675 for more Details

Advertisements

7 thoughts on “Image Upload and Resize

  1. Thanks,
    Awesome article. I find it so hard to find good examples, especially in C#. I am just starting out in ASP.NET and C#.

  2. @altiti To fix the blurriness problem, set InterpolationMode to HighQualityBicubic.

    Also, read the following article; it describes how to fix the remaining bugs in the above code sample: http://nathanaeljones.com/163/20-image-resizing-pitfalls/

    It’s probably better to use a mature image resizing library such as http://imageresizing.net than to try to build your own. The consequences could be as dire as getting hacked or crashing the server constantly.

  3. We are trying to find an application for my smart phone that allows us to take a picture and have the app give us its exact measurements . We could then print it out and have a proportional printed pattern. Can u help …??

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s