Click here to Skip to main content
15,891,864 members
Articles / Web Development / ASP.NET
Article

Function to Resize Images on Upload

Rate me:
Please Sign up or sign in to vote.
3.00/5 (7 votes)
21 Oct 2007CPOL2 min read 57.6K   1.5K   19   9
This is a quick C# function to proportionately resize a JPG based on max width and max height parameters
Screenshot - imgup.jpg
Screen shot of the functionality in my app.

Introduction

I wrote a quick C# function to be used with ASP.NET which accepts the name of an ImageUpload control, a save to path, and max height and max width parameters. It then saves the image (only JPG) file and returns true if there is no error or false if there is an error.

It turned out not to be as simple as it looked or sounds. With referencing through a FileUpload, I had strange a clean up error and files not closing properly. Debugging helped me realise that you can't "use" the same FileUpload control twice. So I have modified the code.

Background

Most articles seem to start with someone trawling around the net to find a solution to something, and then it doesn't quite work, so they make it work and add it here. This is no different.

I self taught myself Visual Basic .NET over the last 6 months, and have currently been learning C# for the last 3 weeks. So my C# isn't the cleanest... but I try. The error handling isn't perfect, but it does the job.

Using the Code

I have updated the code and made the full version available. It is in the form of a Web control, and uses a query string to keep values unique. Make sure your folder has write permissions for the ASPNET account and the SYSTEM (I think those are the two.. not too sure). Drag and drop the control into your ASP.NET page.

My code uses the DropDownBox to select a different filename to upload. You can remove it. I am 99% sure that I dispose and close all open streams and variables properly.

Here is the full Code Behind file:

C#
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class admin_Uploader2 : System.Web.UI.UserControl
{
    public bool ResizeImageAndUpload(System.IO.FileStream newFile, 
	string folderPathAndFilenameNoExtension, double maxHeight, double maxWidth)
    {        
        try
        {
            // Declare variable for the conversion
            float ratio;   

            // Create variable to hold the image
            System.Drawing.Image thisImage = System.Drawing.Image.FromStream(newFile);

            // Get height and width of current image
            int width = (int)thisImage.Width;
            int height = (int)thisImage.Height;

            // Ratio and conversion for new size
            if (width > maxWidth)
            {
                ratio = (float)width / (float)maxWidth;
                width = (int)(width / ratio);
                height = (int)(height / ratio);
            }

            // Ratio and conversion for new size
            if (height > maxHeight)
            {
                ratio = (float)height / (float)maxHeight;
                height = (int)(height / ratio);
                width = (int)(width / ratio);
            }

            // Create "blank" image for drawing new image
            Bitmap outImage = new Bitmap(width, height);
            Graphics outGraphics = Graphics.FromImage(outImage);
            SolidBrush sb = new SolidBrush(System.Drawing.Color.White);

            // Fill "blank" with new sized image
            outGraphics.FillRectangle(sb, 0, 0, outImage.Width, outImage.Height);
            outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);
            sb.Dispose();
            outGraphics.Dispose();
            thisImage.Dispose();

            // Save new image as jpg
            outImage.Save(Server.MapPath(folderPathAndFilenameNoExtension + ".jpg"), 
			System.Drawing.Imaging.ImageFormat.Jpeg);
            outImage.Dispose();

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        //Path to store uploaded files on server - make sure your paths are unique
        string Id = Request.QueryString["id"];
        string filePath = "~\\Image_Upload\\" + Id + "-" + 
			DropDownListImage.SelectedValue.ToString();
        string thumbPath = "~\\Image_Upload\\" + Id + "-" + 
		DropDownListImage.SelectedValue.ToString() + "_thumb";        
        
        // Check that there is a file
        if (fileUploader.PostedFile != null)
        {
            // Check file size (mustn't be 0)
            HttpPostedFile myFile = fileUploader.PostedFile;
            int nFileLen = myFile.ContentLength;
            if ((nFileLen > 0) && 
		(System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".jpg"))
            {
                // Read file into a data stream
                byte[] myData = new Byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);
                myFile.InputStream.Dispose();
                
                // Save the stream to disk as temporary file. 
	       // make sure the path is unique!
                System.IO.FileStream newFile
                        = new System.IO.FileStream
			(Server.MapPath(filePath + "_temp.jpg"),
                            		    System.IO.FileMode.Create);
                newFile.Write(myData, 0, myData.Length);
                
                // run ALL the image optimisations you want here..... 
	       // make sure your paths are unique
                // you can use these booleans later 
	       // if you need the results for your own labels or so.
                // don't call the function after the file has been closed.
                bool success = ResizeImageAndUpload(newFile, thumbPath, 100, 100);
                success = ResizeImageAndUpload(newFile, filePath, 768, 1024);

                // tidy up and delete the temp file.
                newFile.Close();            
  
                // don't delete if you want to keep original files on server 
	       // (in this example its for a real estate website
                // the company might want the large originals 
	       // for a printing module later.
                System.IO.File.Delete(Server.MapPath(filePath + "_temp.jpg"));
            }          
        } 
    }    
} 

Not sure if you need all these.... ? And I think my margins are all out.

Points of Interest

I think there is a way to complete this without saving a temp file then deleting it... but it was the easiest. It can also be expanded for GIF and PNG file types. But the application I need it for only uses JPG.

I have basically re-written this code from two other examples:

History

  • 21st October, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGood Article Pin
Ayesha rana9-Apr-08 23:54
Ayesha rana9-Apr-08 23:54 
GeneralRe: Good Article Pin
Captainobvious10-Apr-08 0:03
Captainobvious10-Apr-08 0:03 
GeneralGreat Example Pin
finsj19695-Nov-07 20:44
finsj19695-Nov-07 20:44 
Generalslight bug in this code Pin
Captainobvious22-Oct-07 21:10
Captainobvious22-Oct-07 21:10 
Generalsome more examples [modified] Pin
rippo22-Oct-07 2:11
rippo22-Oct-07 2:11 
I use something like this, does it all in memory and only saves final image, 2 flavours fit in box or reduces an image to fixed width.... hope it helps

/// Resizes an image and fits into a box.
/// If smaller then nothing is done to the picture
/// If bigger then the longest side is reduced to fit and the smallest
///   side is reduced proportionally
public void FitImageInBox(Stream theImage, Int32 maxWidth, Int32 maxheight, string fullSavePath)
{
    int intNewWidth;
    int intNewHeight;
    int qQuality = 80;
    Image inputImage = Image.FromStream(theImage);
    if (maxWidth < inputImage.Width || maxheight < inputImage.Height)
    {
        if (maxWidth >= maxheight)
        {
            intNewWidth = ((int)((((double)(maxheight)) * (((double)(inputImage.Width)) / ((double)(inputImage.Height))))));
            intNewHeight = maxheight;
        }
        else
        {
            intNewWidth = maxWidth;
            intNewHeight = ((int)((((double)(maxWidth)) * (((double)(inputImage.Height)) / ((double)(inputImage.Width))))));
        }
        if (intNewWidth > maxWidth)
        {
            intNewWidth = maxWidth;
            intNewHeight = ((int)((((double)(maxWidth)) * (((double)(inputImage.Height)) / ((double)(inputImage.Width))))));
        }
        if (intNewHeight > maxheight)
        {
            intNewWidth = ((int)((((double)(maxheight)) * (((double)(inputImage.Width)) / ((double)(inputImage.Height))))));
            intNewHeight = maxheight;
        }
    }
    else
    {
        intNewWidth = inputImage.Width;
        intNewHeight = inputImage.Height;
    }
    try
    {
        Bitmap outputBitMap = new Bitmap(inputImage, intNewWidth, intNewHeight);
        inputImage.Dispose();
        EncoderParameters eps = new EncoderParameters(1);
        eps.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qQuality);
        ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
        outputBitMap.Save(fullSavePath, ici, eps);
        outputBitMap.Dispose();
    }
    catch (Exception ex)
    {
        ExceptionPolicy.HandleException(ex, "GlobalPolicy");
    }
}


/// Reduces an image to a fixed width. If the image is smaller in width then the
/// passed in width then the image is not resized
public bool ReduceImageToFixedWidth(Stream inputImage, int fixedWidth, string fullSavePath)
{
    System.Drawing.Bitmap bmpOut = null;
    int qQuality = 80;
    Bitmap BMPIn = new Bitmap(inputImage, true);
    int NewWidth = 0;
    int NewHeight = 0;
    if (BMPIn.Width < fixedWidth)
    {
        NewWidth = BMPIn.Width;
        NewHeight = BMPIn.Height;
    }
    else
    {
        NewWidth = fixedWidth;
        NewHeight = Convert.ToInt32(BMPIn.Height / (BMPIn.Width / fixedWidth));
    }
    bmpOut = new Bitmap(NewWidth, NewHeight);
    Graphics g = Graphics.FromImage(bmpOut);
    Brush b = new SolidBrush(Color.FromArgb(0, 0, 0));
    g.FillRectangle(b, 0, 0, NewWidth, NewHeight);
    g.DrawImage(BMPIn, 0, 0, NewWidth, NewHeight);
    try
    {
        Bitmap outputBitMap = new Bitmap(BMPIn, NewWidth, NewHeight);
        BMPIn.Dispose();
        EncoderParameters eps = new EncoderParameters(1);
        eps.Param[0] = new EncoderParameter(Encoder.Quality, qQuality);
        ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
        outputBitMap.Save(fullSavePath, ici, eps);
        outputBitMap.Dispose();
        return true;
    }
    catch (Exception ex)
    {
        ExceptionPolicy.HandleException(ex, "GlobalPolicy");
    }
    return false;
}


/// Gets encoder info
private ImageCodecInfo GetEncoderInfo(string mimeType)
{
    int j;
    ImageCodecInfo[] encoders;
    encoders = ImageCodecInfo.GetImageEncoders();
    j = 0;
    while (j < encoders.Length)
    {
        if (encoders[j].MimeType == mimeType)
        {
            return encoders[j];
        }
        Interlocked.Increment(ref j);
    }
    return null;
}

GeneralRe: some more examples Pin
Captainobvious22-Oct-07 2:44
Captainobvious22-Oct-07 2:44 
GeneralRe: some more examples Pin
rippo22-Oct-07 3:23
rippo22-Oct-07 3:23 
QuestionGood Sample, What of Aspect Ratio? Pin
obinna_eke22-Oct-07 0:49
obinna_eke22-Oct-07 0:49 
AnswerRe: Good Sample, What of Aspect Ratio? Pin
Captainobvious22-Oct-07 1:50
Captainobvious22-Oct-07 1:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.