본문 바로가기
Web Program/Asp.net Lecture

New Image Generator control in ASP.Net 3.5

by 현이빈이 2009. 5. 13.
반응형

New Image Generator control in ASP.Net 3.5

 

Introduction

Storing images in database BLOB field and displaying it on aspx page is one of the common tasks we do in asp.net projects.  Asp.Net itself does not have an in build control to bind the image stored in database. To display an image stored in database, we will write an HttpHandler which will fetch the image from database and do a binary write. We all know that doing a binary write will become cumbersome when the number of images increases and the number of users becomes high. This week Microsoft have released a new control called ASP.NET Generated Image control to display image in ASP.Net page. This article will give you a kick start on this control and some of its features. 

 

ComponentArt

Pre-Requisites

Ø       Download the control (Microsoft.Web.GeneratedImage.dll) from here.

Ø       It Requires Visual Studio 2008 and .NetFramework 3.5 Sp1 to work.  You can download .NetFramework 3.5 Sp1 it here.

 

GeneratedImage control in ASP.Net 3.5

This control can be used to display image faster, we can cache the generated image and we can do transformation on the generated image. To display the image, this control uses an Image HttpHandler which can accept parameters using NameValueCollection object. This Image HttpHandler is similar to normal HttpHandler which inherits an abstract class called ImageHandler. This ImageHandler abstract class internally inherits IHttpHandler.

 

public class ImageHandler1 : ImageHandler {

   

    public ImageHandler1() {

        // Set caching settings and add image transformations here      

       }

   

    public override ImageInfo GenerateImage(NameValueCollection parameters) {

       return new ImageInfo();

       }

}

 

The implementation is really simple. Read the image from database as a byte array and convert the byte array to Microsoft.Web.ImageInfo object for the image to display. This object will come as a part of the control dll we are downloading.  ImageInfo object has 2 overloaded constructors, one will take Image object and the other will take a byte array as an argument. We can pass the parameters to this handler by a collection called Parameters in GeneratedImage control. With this information, we will see how we can use this control to display images.

 

Using GeneratedImage control

Once you have downloaded the control, you can add it to the toolbox of Visual Studio 2008 by right clicking and selecting “Choose Items” option on the toolbar.

Displaying Image from Database

1.      Drag a GeneratedImage control from the toolbox. This will add a new GeneratedImage control and @Register directive in the aspx page to register the control.

2.      To add an HttpHandler, you can either click “Create Image Handler” option we get when we click the smart tag or by adding a generic handler through “Add New Items” option we get when we right click the visual studio solution.

CodeDigest.com

 

In GenerateImage() method, read the image from database and pass the image byte array to the ImageInfo constructor.

Refer the below code.

 

public class ImageFromDB : ImageHandler {

   

    public ImageFromDB() {

        // Set caching settings and add image transformations here   

       }

   

    public override ImageInfo GenerateImage(NameValueCollection parameters) {

        // Add image generation logic here and return an instance of ImageInfo

        string imageid = parameters["ImID"].ToString();

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);

        connection.Open();

        SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);

        SqlDataReader dr = command.ExecuteReader();

        dr.Read();    

        return new ImageInfo((Byte[])dr[0]);

    }

}

 

The parameter “ImID” in the above code can be passed from the Parameters collection of the control from the aspx page. The ImageGenerated control will look like,

<cc1:GeneratedImage ID="GeneratedImage1" runat="server"

            ImageHandlerUrl="~/ImageFromDB.ashx">

<Parameters>

   <cc1:ImageParameter Name="ImID" Value="1" />

</Parameters>

</cc1:GeneratedImage>

 

If we execute the page, we will get an output like below,

CodeDigest.com

 

Sponsors

Useful Books For Developers
Learning jQuery 1.3 More books..

Similar Articles

Transformation using GeneratedImage control

To do transformation on the generated image, there is an abstract called ImageTransform which can be implemented. Transformation may be, adding watermark, adding copyright information on the image etc.

 

ImageTransform abstract class

public abstract class ImageTransform

    {

        protected ImageTransform();

 

        [Browsable(false)]

        public virtual string UniqueString { get; }

 

        public abstract Image ProcessImage(Image image);

    }

To understand this better, we will implement a simple watermark with ImageTransform class.

public class WaterMark : ImageTransform

{

       public WaterMark()

       {

              //

              // TODO: Add constructor logic here

              //

       }

 

    public override System.Drawing.Image ProcessImage(System.Drawing.Image img)

    {

        Graphics gra = Graphics.FromImage(img);

         gra.DrawString("www.microsoft.com", new Font("Verdana", 18), new SolidBrush(Color.Green), img.Width / 2, img.Height / 2);

        return img;

    }

}

The above class will add a text www.microsoft.com in the middle of the image.

Using the above transformation class,

public class WaterMarkTransformatiom : ImageHandler

{

    public WaterMarkTransformatiom()

    {

    }

    public override ImageInfo GenerateImage(NameValueCollection parameters) {

 

        string imgurl = HttpContext.Current.Server.MapPath(".")+"\\AutumnLeaves.jpg";

        Bitmap img = new Bitmap(imgurl);

        WaterMark wmImage = new WaterMark();

        return new ImageInfo(wmImage.ProcessImage(img));

    }

}

 

In the above handler, We are reading a image from file system and adding the water mark text by calling ProcessImage() method of WaterMark transformation class. The output will be,

CodeDigest.Com

You can see the word www.microsoft.com on the displayed image.

 

Adding Caching to the control

The ImageHandler object has properties to set both server and client cache. It also has property to set client cache expiration time. This can be set in the constructor of handler that is generating image.

The below code enables client and server cache for the image handler that is generating image from database,

 

public class ImageFromDB : ImageHandler {

   

    public ImageFromDB() {

        // Set caching settings and add image transformations here

        this.EnableServerCache = true;

        this.EnableClientCache = true;     

       }

   

    public override ImageInfo GenerateImage(NameValueCollection parameters) {

        // Add image generation logic here and return an instance of ImageInfo

        string imageid = parameters["ImID"].ToString();

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);

        connection.Open();

        SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);

        SqlDataReader dr = command.ExecuteReader();

        dr.Read();    

 

        this.ImageTransforms.Add(new WaterMark());

        return new ImageInfo((Byte[])dr[0]);

    }

}

원문 : http://www.codedigest.com/Articles/ASPNET/119_New_Image_Generator_control_in_ASPNet_35.aspx

반응형