Click here to Skip to main content
13,148,173 members (41,380 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


13 bookmarked
Posted 22 Feb 2013

Resizing image dynamically using C#

, 22 Feb 2013
Rate this:
Please Sign up or sign in to vote.
Resizing any image using HTTP Handlers.


Resizing an image using HTTP Handlers. We can specify the image height and width and resolution of all images, not particular for an image. So network traffic will be reduced in Web Browser. In this article I'm specifying the image height and width to 100px and resolution to 72DPI. So if any image loads from server it will reduced to 3KB size from any size, and the loading time will be reduced to 2 sec to 500 millisec. If resolution is will be not a great, we can increase the resolution.

If you have any doubts through the code, please read the comments carefully.

I think you'll understand easily 


The images will load in web pages as we uploaded to server. This may cause performance issue. Because of images may be in various size. So we'll develop HTTP Handlers to handle any request before it send to browser. 

Using the code

Add the three namespaces to your handler file

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

The image handling will be processed in ProcessRequest method. Here mainly we need the image path, including the image name, like "\pathtoimage\image.jpg".

Just copy and paste the code in your handler file. If needed change string imagepath according to your requirement.

public class ImgHandler:IHttpHandler
    public ImgHandler()
    // TODO: Add constructor logic here

    public void ProcessRequest(HttpContext context)
        string imagePath = context.Request.QueryString["image"];
        // split the string on periods and read the last element, this is to ensure we have
        // the right ContentType if the file is named something like "image1.jpg.png"
        string[] imageArray = imagePath.Split('.');
        if (imageArray.Length <= 1)
            throw new HttpException(404, "Invalid photo name.");
            if (File.Exists(imagePath))
                //--------------- Dynamically changing image size --------------------------  
                context.Response.ContentType = getContentType(imagePath);
                // Set image height and width to be loaded on web page
                byte[] buffer = getResizedImage(imagePath, 100, 100);
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);

    public bool IsReusable
        get { return true; }

    byte[] getResizedImage(String path, int width, int height)
        Bitmap imgIn = new Bitmap(path);
        double y = imgIn.Height;
        double x = imgIn.Width;
        double factor = 1;
        if (width > 0)
            factor = width / x;
        else if (height > 0)
            factor = height / y;
        System.IO.MemoryStream outStream = new System.IO.MemoryStream();
        Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
        // Set DPI of image (xDpi, yDpi)
        Graphics g = Graphics.FromImage(imgOut);
        g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), 
          new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

        imgOut.Save(outStream, getImageFormat(path));
        return outStream.ToArray();

    string getContentType(String path)
        switch (Path.GetExtension(path))
            case ".bmp": return "Image/bmp";
            case ".gif": return "Image/gif";
            case ".jpg": return "Image/jpeg";
            case ".png": return "Image/png";
            default: break;
        return "";

    ImageFormat getImageFormat(String path)
        switch (Path.GetExtension(path))
            case ".bmp": return ImageFormat.Bmp;
            case ".gif": return ImageFormat.Gif;
            case ".jpg": return ImageFormat.Jpeg;
            case ".png": return ImageFormat.Png;
            default: break;
        return ImageFormat.Jpeg;

Points of Interest

Don't think image will be resized if we mention image height and width in control like

<asp:Image ID="Image1" runat="server" Visible="true"  ImageUrl="imgHandler.ashx?image=d:\\pathtoimage/image.jpg" 
width=150 height=105></asp:Image>>


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


About the Author

Rajendra Pathi
Software Developer Good Company
India India
Interested in R&D tasks and quick solution for problems.
Strong in problem solving skills(C#, ASP.Net, JQuery, Javascript)

You may also be interested in...


Comments and Discussions

QuestionError on Building up the solution Pin
Member 91235133-Sep-14 0:37
memberMember 91235133-Sep-14 0:37 
QuestionQuestion Pin
Melike Melek9-Apr-14 21:40
memberMelike Melek9-Apr-14 21:40 
QuestionTwo related questions Pin
lalula1225-Mar-14 16:39
memberlalula1225-Mar-14 16:39 
Questionsaving the image Pin
Lima314-Nov-13 6:31
groupLima314-Nov-13 6:31 
Questionimage resizing code Pin
Wollaston24-Mar-13 22:03
memberWollaston24-Mar-13 22:03 
SuggestionYou should be disposing your resources ... Pin
stooboo22-Feb-13 7:56
memberstooboo22-Feb-13 7:56 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170924.2 | Last Updated 22 Feb 2013
Article Copyright 2013 by Rajendra Pathi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid