close

Trust Me!! Trust You!!


  • Blog
  • Local Log
  • Tag Cloud
  • Key Log
  • Guestbook
  • RSS Feed
  • Write a Post
  • Admin

혹시 블로그 스킨이 깨져 보이시나요? 최신버전의 Internet Explorer(Windows용), Opera, Firefox를 사용해보세요.

New Image Generator control in ASP.Net 3.5

웹 프로그래밍
2009/04/20 17:20
 

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. 

 

Click Here

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
ASP.NET 3.5 Social Networking More books..

Similar Articles
Using HyperLink Control in DataBound Controls
Posted on 4/12/2009 @ 8:57 AM By ph madala
Picasa Style Photo Album Using ListView Control in ASP.Net 3.5
Posted on 4/9/2009 @ 9:36 AM By Satheesh Babu
Better Practices on Building High Performance Web Pages
Posted on 4/2/2009 @ 8:09 AM By balamurali balaji
Edit,Update and Delete in GridView using DataKeys
Posted on 4/1/2009 @ 7:54 AM By ph madala
Creating RSS Feeds using Repeater and DataSource controls in ASP.Net
Posted on 3/30/2009 @ 5:47 AM By Satheesh Babu

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!!

이올린에 북마크하기
No received trackback. / No comment.

Trackback Address :: http://viper150.cafe24.com/trackback/84

You can also say.

Prev 1 ... 215 216 217 218 219 220 221 222 223 ... 298 Next
블로그 이미지
이것저것 불펌금지도 퍼다가 담습니다. 외부에 비공개된 페이지 입니다. By. 어른왕자

카테고리

  • 전체 (298)
    • 사는 이야기 (115)
    • 웹 프로그래밍 (102)
    • App 프로그래밍 (22)
    • IT 뉴스&기타 (22)
    • 박한별 (4)
    • 역사&기타지식 (9)

태그목록

  • 전산공무원
  • 박근혜
  • 장애인
  • 달걀찜
  • 프레젠테이션 매거진
  • 터키
  • vga성능
  • 획갈림
  • svn
  • 최적화
  • 운동
  • 스프링 인증
  • 자바스크립트 마우스 막기
  • 생산성
  • 고구려
  • 실시간tv
  • 경찰
  • 생산성저하
  • 사회초년생
  • Button
  • 625
  • iphone
  • 이클립스 루트
  • getRealPath
  • 스케줄링
  • 사진
  • 드라마
  • 집안일
  • 레지스트리
  • SLRCLUB

최근에 올라온 글

  • 보험사의 조정신청 대응방법.
  • 어느 천재의 앞선 시선.
  • [병맛더빙] 누구게..... (1)
  • 韓경제 `회색 코뿔소` 상황...
  • SVN Connector 설치 URL.
  • 군대를 가지 않는 서울대생.
  • “운은 하늘의 귀여움 받는...
  • 목장에서 알바하다가 캐스...
  • [펌]믿고 거르는 관상.
  • 하루에 1세트씩 하면 좋다...

최근에 달린 댓글

  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22

최근에 받은 트랙백

  • công ty may đồng phục. công ty may đồng phục 01/08
  • Israelnightclub`s recent blo... Israelnightclub`s recent blo.. 01/06
  • Suggested Browsing. Suggested Browsing 01/06
  • similar site. similar site 01/06
  • לאתר הבית שלנו. לאתר הבית שלנו 01/06

글 보관함

  • 2019/03 (1)
  • 2018/12 (1)
  • 2018/09 (1)
  • 2018/08 (1)
  • 2018/02 (1)

달력

«   2021/01   »
일 월 화 수 목 금 토
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            

링크

  • Total : 261975
  • Today : 8
  • Yesterday : 42
Tattertools
Eolin
rss

어른왕자's blog is powered byTattertools1.1.2.2 : Animato