Click here to Skip to main content
Click here to Skip to main content

Tagged as

Resizing image dynamically using C#

, 22 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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.");
        }
        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)

Share

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)

Comments and Discussions

 
QuestionError on Building up the solution PinmemberMember 91235133-Sep-14 1:37 
QuestionQuestion [modified] PinmemberMelike Melek9-Apr-14 22:40 
QuestionTwo related questions Pinmemberlalula1225-Mar-14 17:39 
Questionsaving the image PingroupLima314-Nov-13 7:31 
Questionimage resizing code PinmemberWollaston24-Mar-13 23:03 
SuggestionYou should be disposing your resources ... Pinmemberstooboo22-Feb-13 8:56 

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

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

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