Click here to Skip to main content
15,867,330 members
Articles / Web Development / ASP.NET
Tip/Trick

Resizing image dynamically using C#

Rate me:
Please Sign up or sign in to vote.
4.91/5 (8 votes)
22 Feb 2013CPOL1 min read 120K   13   6
Resizing any image using HTTP Handlers.

Introduction 

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 

Background 

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

C#
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.

C#
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.");
        }
        else
        {
            if (File.Exists(imagePath))
            {
                //--------------- Dynamically changing image size --------------------------  
                context.Response.Clear();
                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);
                context.Response.End();  
            }
        }
    }

    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)
        imgOut.SetResolution(72,72);  
         
        Graphics g = Graphics.FromImage(imgOut);
        g.Clear(Color.White);
        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>>
.

License

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


Written By
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)

Comments and Discussions

 
QuestionError on Building up the solution Pin
Member 91235133-Sep-14 0:37
Member 91235133-Sep-14 0:37 
QuestionQuestion Pin
Melike Melek9-Apr-14 21:40
Melike Melek9-Apr-14 21:40 
QuestionTwo related questions Pin
lalula1225-Mar-14 16:39
lalula1225-Mar-14 16:39 
Questionsaving the image Pin
Lima314-Nov-13 6:31
Lima314-Nov-13 6:31 
Questionimage resizing code Pin
Wollaston24-Mar-13 22:03
Wollaston24-Mar-13 22:03 
SuggestionYou should be disposing your resources ... Pin
stooboo22-Feb-13 7:56
stooboo22-Feb-13 7:56 
http://msdn.microsoft.com/en-us/library/system.drawing.graphics.dispose.aspx[^]

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.