CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
New Image Generator control in ASP.Net 3.5

By Satheesh babu
Posted On Aug 21,2008
Article Rating:
Average Rating: 5
No of Ratings: 2
No of Comments: 26
Category: ASP.Net 3.5
Print this article.

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. 

 

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

 




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]);

    }

}

 

Downloads

Source Code

 

Conclusion

This article will help us to understand some of the basic usage of the new Image Generated control in ASP.Net 3.5. We will see more about this control in coming days. This control can also be used to render texts as image using the handlers. The source code has option to upload the images too. Download the code attached with this article to understand it better. This article is written by taking the sample codes available in codeplex as reference.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
imagesupload
i want to open the fileupload the image is open directly how to do i take that
Printing image from IE?
Hi,
Using a handler for images works great for displaying the image.
But, I'm finding in IE, that when I righ-click to get the popup menu and then click 'Print Picture' the image does not print ... that is a blank page prints.
Any idea how to get 'Print Picture' to print using this virtual url?
Thanks.
Kim
Does not work with postbacks
Unfortunately this control does not work when a postback (sync or async) occurs and required rebinding.

Any workarounds?
Can this do PostBack?
Hi,

Thank you for this, I've been looking for this for about a week. and was about to hand code it from scratch...

I seem to be having trouble with PostBack? I'm using this in a Datalist, and I have a few other user Controls on screen. If one of the other controls fires a PostBack I'm getting the HttpHandler tossing up an error "near="

I thought somthing like this might solve it by adding it the HttpHandler but it didn't work?:
public override ImageInfo GenerateImage(NameValueCollection parameters) {
if (parameters["ImID"] == "null"){
do nothing
}
else{
gimmie some sugar
}

image
I've needed this for a while now. Thanks
THANKS
VERY IMPORTANT ONE
Awsome New Image Generator control in ASP.Net 3.5
Scott hunter and the crew did a good job on this one This articale put it all it all to gether But I only get one picture out of the data base how do ai set the the Parameters to iterate through the data base and return all the pictures in the table
Code in vb please
Could you please give the code in vb. i m not able to return back the byte in imageinfo.
thanx
Can someone post the GridView with ImageGenerator Code
Can someone post the GridView with ImageGenerator Code?
Client cache
this.EnableClientCache = true;

has anyone had a problem with this?

The control was just what I needed for a project I'm working on. However, server cache works fine but client cache seems to be ignored. "Fiddler" shows me the web page is always gong back to the server for the image.
Alternative
For the sake of competition, there is a free open source control that have similar functionality but maybe a little bit easier to use http://www.sharppieces.com/demo/databaseimage.aspx .
control saves images to disk
I just read through the source code and the control seems to write the images to the disk after it read them from the DB. How about keeping the images in the server cache instead of reading them from the disk? Of course you can do that only if you have a limited number of images.
No Linq support
I tried everything I could. Just letting you know
why is sp1 required?
Why is .net 3.5 sp1 required? My hosting provider is not yet ready to install sp1, is there a way to get this to run without sp1? Would love to be able to use this control.
RE:Please explain
Hi Andrew, Thanks for your feedback. As we know, during request processing if the number of request or file size is huge, it is defentely going to affect the worker process performance becoz we are performing binary write where the stream is going to reside in the process memory. This will lead to worker process recycle if the memory consumption is huge when no of request grows. Also, if we see the request processing cycle it will be from inetinfo-->isapi-->aspnet_wp and hence we will see a degardation during rendering large number of request involving images. This control has some caching techniques both in server as well as client to improve performance.
RE:Could be open for sql injection...
Hi Mikkel, Thanks for your valuable feedback! You are correct, since i took this article to explain the new imagegenerator control quickly i just hardcoded the query otherwise would have used SP's which would normally handled the problem..Thanks again!!
Could be open for sql injection...
Nice. However, this code could be open for sql injections: SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection); You should use parameters when using a SqlCommand object. If you do not do this... you could open your database for sql injections.
Exelent
Exelent
Nice One
Nice Informative Article.Never heard of this control before. This control really did a ease of getting images from DB.
Please explain
Why do you say "We all know that doing a binary write will become cumbersome when the number of images increases and the number of users becomes high." ? How does MS deal with the cumbersomeness with high numbers of users/images?
Excelent
Good article
New Image Generator control in ASP.Net 3.5
Good article....
RE:Use within GridView/DetailsView
Hi guru, Good to hear that it worked! Thanks for your comments!
RE:Use within GridView/DetailsView
Thanks Satheesh. I did try it and it worked perfectly. Regards, GB
RE:Use within GridView/DetailsView
Hi Guru, Ofcourse, we can do that! Regards, Satheesh
Use within GridView/DetailsView
Thanks for your Article. I was just wondering what if we want to display images in a field in DetailsView? or say in a grid view. Can we use this control ? or there we have a choice of BinaryWrite only? Regards, GB