Extending the asp:image control to set a maximum width

In this example, we are going to extend the control to allow a MaxWidth proprety, which will limit the size of the image to that value, if it is specified.
Create a new class called MaxWidthImage.cs in your App_Code folder and add the following code:
using System;using System.Web;using System.Web.UI.WebControls;namespace MyNameSpace{public class MaxWidthImage : Image{    private int _MaxWidth;    public int MaxWidth    {        get        {            return _MaxWidth;        }        set        {            _MaxWidth = value;        }    }    protected override void OnPreRender(EventArgs e)    {        if (string.IsNullOrEmpty(ImageUrl)) return;        using (System.Drawing.Image MyImage =            System.Drawing.Image.FromFile            (HttpContext.Current.Server.MapPath(ImageUrl)))        {            int CurrentWidth = MyImage.Width;            if (MaxWidth != 0 && CurrentWidth > MaxWidth)            {                CurrentWidth = MaxWidth;            }            Attributes.Add("width", CurrentWidth.ToString());        }    }}}

Leave a Reply

Your email address will not be published. Required fields are marked *