web 2.0

Image Resizing in ASP Dot Net with C# using httphandler

Considering the reader has a prior knowledge of HttpHandler and ISAPI filtering
by IIS.
Some times we need an image to be re sized (to lower dimensions) without 
distortion and proportional to the original dimensions of image in ASP.Net
Along with the above requirement, the code is also specifying how to 
merge two images in Dot Net using graphics components.
So the following code is helpful in that case.
In the code, there is just a general .ashx page in dot net that implements
iHttpHandler interface and defining it's method "ProcessRequest" that 
is automatically called when there is call to it.
The color attribute is optional (however left as an assignment for the reader),
which is used to color the remaining portion of the final image,the area less 
than the required height width (e.g. our requirement of output image is 180 X 135,
but final image comes out to be 170 X 120 because of it's origional proportions,
so if we want to fill that 10 X 10 with a color, we will send the parameter with
the url we are calling it from to manage color of the background)
The ashx code is :
(If the paths are static, use your own locations here)
<%@ WebHandler Language="C#" Class="HttpImageHandler" %>
using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public class HttpImageHandler : IHttpHandler
{
    int iWidth = 0;
    int iHeight = 0;
    string strColor = "White";
    /// <summary>
    /// Includes photos path of the users with "/" in the end
    /// </summary>
    public static string strPhotosPath = HttpContext.Current.Server.MapPath("./");
    public void ProcessRequest(System.Web.HttpContext context)
    {
        if (context.Request.Params["height"] != null)
        {
            try
            {
                iHeight = int.Parse(context.Request.Params["height"]);
            }
            catch
            {
                iHeight = 0;
            }
        }
        if (context.Request.Params["width"] != null)
        {
            try
            {
                iWidth = int.Parse(context.Request.Params["width"]);
            }
            catch
            {
                iWidth = 0;
            }
        }
        if (context.Request.Params["color"] != null)
        {
            try
            {
                strColor = context.Request.Params["color"].ToString();
            }
            catch
            {
                strColor = "White";
            }
        }
        string Image = context.Request.Params["imgPath"];
        if (Image == null)
        {
            this.ErrorResult();
            return;
        }
        Bitmap bmp;
        bmp = CreateThumbnailLightYelloBack(Image, iWidth, iHeight);
        if (bmp == null)
        {
            this.ErrorResult();
            return;
        }
        // Put user code to initialize the page here
        HttpContext.Current.Response.ContentType = "image/jpeg";
        bmp.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        bmp.Dispose();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private void ErrorResult()
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.StatusCode = 404;
        HttpContext.Current.Response.End();
    }
    public static Bitmap CreateThumbnailLightYelloBack(string lcFilename, int lnWidth, int lnHeight)
    {
        System.Drawing.Bitmap bmpOut = null;
        try
        {
            try
            {
                lcFilename = strPhotosPath + lcFilename;
            }
            catch
            {
                lcFilename = strPhotosPath + "guypic.gif";
            }
            Bitmap loBMP = new Bitmap(lcFilename);
            int lnNewWidth = 0;
            int lnNewHeight = 0;
            /*Actual Height & Width*/
            lnNewWidth = lnWidth;
            lnNewHeight = lnHeight;
            string xCol = "#00000";
            Color c = System.Drawing.ColorTranslator.FromHtml(xCol);
            decimal actualHeight = (decimal)lnNewHeight, actualWidth = (decimal)lnNewWidth;
            if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
            {
                actualHeight = (decimal)loBMP.Height;
                actualWidth = (decimal)loBMP.Width;
            }
            else
            {
                if (loBMP.Height > loBMP.Width)
                {
                    actualHeight = (decimal)lnHeight;
                    actualWidth = (decimal)((float)loBMP.Width / (float)loBMP.Height) * lnHeight;
                }
                else if (loBMP.Width > loBMP.Height)
                {
                    actualWidth = (decimal)lnWidth;
                    actualHeight = (decimal)((float)loBMP.Height / (float)loBMP.Width) * lnWidth;
                }
            }
            float fltMarTop = 0, fltMarLef = 0;
            if (lnWidth > actualWidth)
            {
                fltMarLef = (float)lnWidth - (float)actualWidth;
                fltMarLef /= 2;
            }
            if (lnHeight > actualHeight)
            {
                fltMarTop = (float)lnHeight - (float)actualHeight;
                fltMarTop /= 2;
            }
            SolidBrush brushForImage = new SolidBrush(c);
            bmpOut = new Bitmap((int)actualWidth, (int)actualHeight);
            //bmpOut = new Bitmap(lnWidth, lnHeight); // For giving the back color
            bmpOut.MakeTransparent(c);
            Graphics g = Graphics.FromImage(bmpOut);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //g.FillRectangle(brushForImage, 0, 0, (int)actualWidth, (int)actualHeight);
            //g.FillRectangle(brushForImage, 0, 0, lnWidth, lnHeight);
            g.DrawImage(loBMP, 0, 0, (int)actualWidth, (int)actualHeight);
            
            #region Premium Start Show
            loBMP = new Bitmap(@"E:\PUNEET\Miscellaneous\ImageResizing\star.png");
            g.DrawImage(loBMP, (int)actualWidth - 14, 0, 14, 14); // Size of star to be merged
            #endregion
            
            loBMP.Dispose();
        }
        catch
        {
            return null;
        }
        return bmpOut;
    }
}
As i have following image :

And my required output is :

And another required output is :

Calling the handler on aspx page :
Inline Code goes as :

        <div>
            <div style="width: 180px; height: 135px; float: left; border: 1px solid red">
                <img runat="server" id="imgUser" />
            </div>
            <div style="width: 53px; height: 44px; float: left; border: 1px solid red;margin-left:15px;">
                <img runat="server" id="imgSmallUser" />
            </div>
        </div>
And Code behind goes as : using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Give path to your website here imgUser.Src = "http://localhost:2444/ImageResizing/ImageHandler.ashx?imgPath=me.gif&height=130& width=180&color=LessLighterYellow"; imgSmallUser.Src = "http://localhost:2444/ImageResizing/ImageHandler.ashx?imgPath=me.gif&height=44&width=53& color=LessLighterYellow"; } }

Tags: , , , , , , ,

ASP.NET