German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Save and Display Images using ASP .NET 2.0 Profile

Written by omerkamal on Mar 08, 2007
How to save and show an Image/Picture using ASP .NET 2.0 Profiles

Explanation:

We already included some Articles about displaying Image in ASP .NET. It was about displaying and saving an Image in MS SQL Database.
 
 
Saving an Image to Profile:

ALL data types which are Serealizable can be saved in the Profile. Serialization is the process of saving the state of an object by converting it to a stream of bytes. The object can then be persisted to file, database, or even memory. The reverse process of serialization is known as deserialization . (see the following Figure)




Uses of serialization

Serialization is used in many scenarios, but the main purpose is to save the state of an object in order to have the ability to recreate the same object when required. It is an important to let the user save work and then be able to continue from that point at a later time. This is a common need in various tools and applications. Serialization is also used in creating a clone of an object.

Another important need for serialization arises when the object is required to travel electronically over wire. In such cases the objects are serialized and deserialized. In fact, serialization is one of the fundamental requirements for techniques such as .NET Remoting.

Even the hibernation mode in the Windows Operating system can be considered a form of serialization.

Image serialization

S erialization is an important entity of pipelining an Object from one point to other point. The .NET Framework provides certain built-in mechanisms which can be used to serialize and deserialize objects. This functionality can be found in the System.Runtime.Serialization. and the System.Xml.Serialization namespaces of the .NET Framework

 
Here we will restrict our discussion to serialization of an Image. Image is serialized as a binary data to the Database or a file.
 
In ASP .NET to show an Image from a location would be an easy target as we can use simply “src” property of an Image control with pointing it to the image file location and every thing will be fine. But harder efforts need to perform when we want to show an image from Database.
 
Saving an image to a database is a different story also. It needs different programming technique to store a binary data (Image) into a database rather then saving it (Image) to a file location.
 
After long theoretical Introduction now we are able to describe the methods to save/retrieve an Image to/from a Profile (as Profile is also saving data to a Database).
 
The 1st step will be to tell the Web server/Database server that you are adding a new field to the User Profile system. We will perform this like the following:
 
<profileenabled="true"automaticSaveEnabled="false" >
      <properties>
 
-----other properties come here------
 
             <addname="Picture"
                  type="System.Drawing.Bitmap"
                  serializeAs="Binary"/>
      properties>
    profile>
 
You noticed that the Data type is a “Bitmap”. Why not an Image? Image is an Abstract class which is meant to Inherit. This is a base class that provides functionality for the Bitmap and Metafile descended classes.
 
Abstract classes are like Interfaces with the difference that methods and properties of an abstract Class can contain different types of Accessor where as an Interface does not contain any type of Accessor i.e. it is solely created to implement.
 
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
 
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Constants
Only Static final constants.
Both instance and static constants are possible.
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If the various implementations only share method signatures then it is better to use Interface.
If the various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
 
 
 
To save the Image in Profile would be more easy assignment then retrieving from the Profile. See the following code for saving an Image:
 
ProfileCommon prof = Profile.GetProfile("UserName");
prof.Picture = new System.Drawing.Bitmap(
                           Server.MapPath(@"ImageFolder\Logo-Stars.png"));
prof.Save();
 
We retrieved the user profile, created a new bitmap and then assigned it to the Profile Field.
To Retrieve the Image we need to cerate a Binary stream. For this we will use System.IO Namespace.
 
Now, the hard story starts. As we said that we will load an image using a stream. Normally, we can do this by cerating a Method which return type is a stream. In ASP .NET its not easy to display image as tage loads an Image using src attribute. This only allows a file or a web page path to load an Image. So what is the solution? Yes there is a solution. In ASP .NET we use a handler for this reason.
 
What is a Handler?
A handler is responsible for fulfilling requests from a browser. Requests that a browser manages are either handled by file extension (or lack thereof) or by calling the handler directly. Only one handler can be called per request. A handler does not have any HTML static text like .aspx or .ascx files. A handler is a class that implements the IHttpHandler interface. If you need to interact with any Session information, you will also need to implement IRequiresSessionState. If you want to make an asynchronus handler, you will need to implement the IHttpAsyncHandler interface instead of the IHttpHandler interface.

Calling a Handler by File Extension
A handler can be invoked by any file extension that is mapped via the web.config and the IIS file extension mappings. You can have a file named something.billybob where 'billybob' is the file extension, or you can have no file extension at all such as http://web/handler/file where a request for 'file' without an extension invokes a handler mapped to *.* or the directory as *.

Calling a Handler Directory
The code file for the handler has the file extension of 'ashx' on the web server. This file can be called directly via a browser without having to set up web.config or IIS file extension mappings. For example: http://web/handler/handler.ashx.
Some examples of this hander type are photo albums, RSS feeds, and blogging sites. Each of these is a good example of work that can be better accomplished without standard HTML. A photo album involves directory crawling and responding with pictures. A RSS feed returns information in the correct format.
If you cerate a Handler with visual studio it will look like this:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

By browsing this Handler we will get a Text "Hello World" in our page. If you noticed that we always have to copy our data to the Context. Data can wrote to context either as a Text or as a Binary data.

When we want to copy a simple text to the Context we use Response.Write() method but how to Copy a Binary data? As we discribed earlier Image is a binary data (in GDI Langauge it’s a Two dimesional Array of Pixels. Don’t mix these two defination as both are ture i.e. Two dimensional data is saved in binary Format). We use Response.OutputStream.Write () to write a Binary data to the Context.

There is a little different senario in Plan C# Application (GDI, GDI+) that we use the Bitmap.Save() method instead for saving the Binary data to out put stream. So don’t get confuse in here because in Web page development our stream needs to Serialized to the Client Context that’s why we use Response.OutputStream.Write ().

I guess this was kind of simple to undertsand the difference. Now the question comes which Overload method we can use to write an Image to the Outputstream of the Context? We will use the method which takes Byt array of the Binary Data. Now see how dows our code look like this:

public void ProcessRequest(HttpContext context)
{
   context.Response.ContentType = "image/jpeg";
   context.Response.Cache.SetCacheability(HttpCacheability.Public);
 
   ProfileCommon prof = new ProfileCommon();
   ProfileCommon prof2 = prof.GetProfile(context.Request.QueryString["UserName"]);
   Bitmap myBitmap = prof2.Picture;
       
   byte[] b = GetImageBytes(myBitmap);       
   context.Response.OutputStream.Write(b, 0, b.Length);
 }

We created a Profile Object then used its method to fill the other object, with the User Profile Data. We can not do this in one line because we need a Profile Object before we can use its method GetProfile(). As in Handler Context we can not access the Page Methods. Where context.Request.QueryString["UserName"] is used to access the Qureystring member “UserName” (we will account this later when we pass a member to the Handler).
What if we want to access an image from a File location? In this senario we need a Page Object as it contains the Server.Map() method. This will look like the following:
 

Page pg = new Page();
Bitmap myBitmap = new Bitmap(pg.Server.MapPath(@"ImageFolder\Logo-Stars.png"));

 
Now see how to convert the Bitmap to a byte Array.
 

private byte[] GetImageBytes(Image image)
{
        ImageCodecInfo codec = null;
 
        foreach (ImageCodecInfo e in ImageCodecInfo.GetImageEncoders())
        {
            if (e.MimeType == "image/png")<
            {
                codec = e;
                break;
            }
        }
 
        using (EncoderParameters ep = new EncoderParameters())
        {
            ep.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
 
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, codec, ep);
                return ms.ToArray();
            }
        }
   }

This is actually the main trick. If you try to save the Image stream in a Stream format to the outputstream it will simply not work because Data is Transferred/Transmited in the Bytes format. So we have to convert the Stream in Bytes first before sending it int to the Pipeline.
 
Now the last point comes how to assign the Handler to a Tage? Its very simple:
 

<img runat="server" id="image" src="ProfilePicHandler.ashx?UserName=SomeName" alt="Profile Image" />

 
Here we are passing a Qureystring member “UserName” to the Handler. Values after “?” come in the account of Querystring and it can be accessed at the Distination Page. Here Mamber Name is “UserName” and its value is “SomeName”.
 
If you are planing to make a Dynamic generation users profile images then you can use code behind instead. But, you have to get the UserName from any source. The source could be a Membership and MembershipUser Objects.
 

public void uploadUserPictures()
{
     MembershipUserCollection users = Membership.GetAllUsers();
     foreach (MembershipUser user in users)
      {
         image.sr = "ProfilePicHandler.ashx?UserName="+user.UserName;
      }
 }
 
 
So our whole code of the Handler will look like this:
 
<%@ WebHandler Language="C#" Class="ProfilePicHandler" %>
 
using System;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using System.IO;
using System.Web.UI;
using System.Drawing;
using System.Drawing.Imaging;
 
public class ProfilepicHandler : IHttpHandler {
 
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
 
        ProfileCommon prof = new ProfileCommon();
        ProfileCommon prof2
               = prof.GetProfile(context.Request.QueryString["UserName"]);
        Bitmap myBitmap = prof2.Picture;
       
        byte[] b = GetImageBytes(myBitmap);       
        context.Response.OutputStream.Write(b, 0, b.Length);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
 
    private byte[] GetImageBytes(Image image)
    {
        ImageCodecInfo codec = null;
 
        foreach (ImageCodecInfo e in ImageCodecInfo.GetImageEncoders())
        {
            if (e.MimeType == "image/png")
            {
                codec = e;
                break;
            }
        }
 
        using (EncoderParameters ep = new EncoderParameters())
        {
            ep.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
 
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, codec, ep);
                return ms.ToArray();
            }
        }
    }
 
}

Hope it Help.
Visitors/Readers Comments
(for questions please use The Forum)



briiin
Yep this answers it all,
thank you very much OmerKamal. You are the saviour

11/03/2007 22:42:09 UTC

Svan
Very nice! Easy, straight-forward solution which does the trick. Thanks a lot!

28/05/2007 09:02:20 UTC

karthikeyan
how to display image from database in single column of gridview using c# 2.0

30/08/2007 04:13:13 UTC

chawba3ainak
how to display image from MS Access database in gridview using c# 2.0 or vb.net

08/09/2007 05:00:49 UTC

Omer Kamal

What ever Database you use the method of Saving and Retrieving an Image is same. you just need to use the Proper Database Accessing object. In your case you will Change the SqlDbConnection with OleDbConnection. Read this for more Detail:

https://dotnet-friends.com/Articles/ASP/ARTinASPffb8509f-5dc4-4765-9c25-cb2087a5994d.aspx

09/09/2007 05:22:21 UTC

Lalit
I have a Problem with retriving an image from sql server 2005 in a datalist.

16/09/2007 02:38:26 UTC

Roy

How can I modify your code to save  a web image url that is loaded in an .aspx web form on every one minute refresh?

 

pls advise

 

thanks in advance

Roy

Singapore

03/10/2007 20:57:55 UTC

Omer Kamal

Hi Roy!

Theoretically, you need to use JavaScript for getting Timer. Then you can execute the Callback Method after every requierd Interval.

09/10/2007 06:43:25 UTC

Rangaraj
I want to display The image from access database to gridview control using asp.net codings any one help me

12/10/2007 00:58:57 UTC

Umesh Kumar
How to fetch image data from database and display image in GridView

17/10/2007 03:02:13 UTC

Kamal

17/10/2007 05:19:58 UTC

neha
 hi.....thank u.......................

23/10/2007 03:48:59 UTC

geethas
if i have the present date and if i click the button in another textbox it automotically shows the after tendays date......i want the code for that.....

05/11/2007 23:14:03 UTC

Starbuck

 Thanks for the post, I had not thought of handling image retrieval this way.  As an alternative to your GetImageBytes method, I added some of my own code... perfect for when you just want to grab an image from a database:

string strImageID = context.Request.QueryString["id"];
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ToString());
string sql = "SELECT imageThumb FROM Images WHERE imageID = " + strImageID;
conn.Open();
SqlCommand command = new SqlCommand(sql, conn);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
byte[] b = (byte[])dr["imageThumb"];
conn.Close();
context.Response.OutputStream.Write(b, 0, b.Length);

 Cheers.

02/12/2007 21:53:49 UTC

ashraf

hi......

dear friend plz help me......

i want know how to store image in database of sql........

Plz ..................

08/12/2007 05:24:09 UTC

anon
good

11/12/2007 07:24:14 UTC

arthi

hi friends,

i tried, but i'm getting System.Byte[]

can any one help me....

13/12/2007 21:59:28 UTC

Rockey
Thanks For Replay

14/12/2007 23:58:09 UTC

pankaj mishra

hi

in sql server stores image datatype.whichn form as a doc file in encrypted format how we can reterive in doc file fronm sql server as a doc format. 

17/12/2007 11:09:44 UTC

Tarik Guney
Hey I just wanna make an addition to this entry :

If you have a FileUpload on your page and If you wanna upload an image to your server, you can use this way too :

bytes[] bytesOfDesiredPicture = fileUpload1.GetBytes;
Stream str = new Stream(bytesOfDesiredPicture);
 blah blah...

15/01/2008 19:29:23 UTC

rizwan memon
hello ! n hi to all asp.net master please help me in asp.net project i m in tybca i m in big trouble plz hel me........................................

21/01/2008 21:26:00 UTC

rizwan memon
my contact no : 9328085683........

plz my little angle save me.....before i crash.....................

21/01/2008 21:28:08 UTC

rizwan memon
my email address : ........

21/01/2008 21:28:56 UTC

Md. Aminul Islam
Can any one tell me how can i show an image from database to a specific location like image control for asp.net in c#

24/01/2008 02:51:18 UTC

nitin

 i sue dur code but i m gettin lots of errors

29/01/2008 02:49:04 UTC

Raj

Out of world!

Can't Understand? 

05/02/2008 12:08:34 UTC

BABU

HOW CAN I DISPLAY THE DOC FILE(IN WHICH CIRCLE , TEXT,ETC) ON THE WEB PAGE IN ASP.NET AND ALSO WHICH CONTROL IS USED TO DISPALY THE DOC FILE.

 

28/02/2008 02:38:51 UTC

suresh

when we are moving the data into stage server we are getting an error Skip Navigation Links. And we are not able to see the sub items of a header menu

 

23/04/2008 06:58:05 UTC

kamal

suresh,

I am not clear what you are asking. Please explain your question.

24/04/2008 15:59:54 UTC

Soumya
Hi,
         It is a nice post.

Is there any way to convert the contents of word file to Byte[ ] Array ?

25/04/2008 01:05:32 UTC

Kumar.J
display the image in ms word from asp.net using c# language.

12/05/2008 04:50:02 UTC

minakshi Patel
hi ,thanks, very good article. I upload the image and stored it in image1 folder. i want to display this image in image control when the aspx page is load in browser. Give me some exmaple or sample code as soon as possible. I need it urgently. Please help me. For this i am thankful to u.

15/05/2008 00:13:56 UTC

kamal
if you saved an image in a folder then you just need to link :

<asp:Image ID="Image1" ImageUrl="~/TopFolder/Nextfolder/ImageName.jpg" runat="server"/>


15/05/2008 02:01:50 UTC

poo
i want to retrieve the image from the database and it will be display in gridview with pagination concept

18/05/2008 23:21:14 UTC

Loganathan.P
   when i selecting image from fileupload control that image display in image control

how to display at runtime in asp.net c# language...

28/06/2008 03:24:18 UTC

sheeja
Hi,

Too good , Its was a great help to me..............

Thanks a lot...................

13/08/2008 01:50:08 UTC

aravind
Its not working

13/08/2008 05:21:12 UTC

Subbu!!!!
I have a Problem with retriving an image from sql server 2005 in a datalist.


Plz help meee out!!!!


I have used the handler files only. The handler files are supported for Gridview, but the images are not displayed in datalist!!!!


Please help meee out!!

26/08/2008 11:44:40 UTC

xolani
my picture is stored  as binary data

09/09/2008 13:42:51 UTC

sharon
 Hi,

 

table code:
CREATE TABLE [dbo].[PictureTable] (
[ImageID] [int] IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[DateAdded] [datetime] NULL ,
[MIMEType] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Image] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO



front end code:

<
I am trying to retrieve all the images from sql server database using asp.net, vb but instead, i keep getting the following text in each image feild "System.Byte[]".

The code that i am using so far is show below. Can someone please help me?

Thank you

Sharon

asp:Repeater ID="Repeater1" runat="server">

 

<HeaderTemplate>

 

<table width="400" border="1">

 

<tr>

 

<th>ImageID: th>

 

<th>Title: th>

 

<th>Image: th>

 

tr>

 

HeaderTemplate>

 

<ItemTemplate>

 

<tr>

 

<td><%# Eval("ImageID") %>td>

 

<td><%#Eval("Title")%>td>

 

<td><%# Eval("Image") %>td>

 

tr>

 

ItemTemplate>

 

<FooterTemplate>

 

table>

 

FooterTemplate>

 

 

 

 

 

DBCmd =

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadDim DBConn As New SqlConnection(GlobalApp.GetConn)Dim DBCmd As New SqlCommandDim reader As SqlDataReaderNew SqlCommand("Select ImageID, Title, Image from PictureTable", DBConn)Try

DBConn.Open()

reader = DBCmd.ExecuteReader()

Repeater1.DataSource = reader

Repeater1.DataBind()

reader.Close()

 

Response.Write(

 

Catch ex As Exception"ERROR ERROR! Can not retrieve images")Finally

DBConn.Close()

 

End Try

 

End

End Sub Class
asp:Repeater>


back end code:

11/09/2008 05:23:59 UTC

Sharon

 

 

 

DBCmd =

 

Sorry, full code is below



Dim
DBConn As New SqlConnection(GlobalApp.GetConn)Dim DBCmd As New SqlCommandDim reader As SqlDataReaderNew SqlCommand("Select ImageID, Title, Image from PictureTable", DBConn)Try

DBConn.Open()

reader = DBCmd.ExecuteReader()

Repeater1.DataSource = reader

Repeater1.DataBind()

reader.Close()

 

Response.Write(

 

Catch ex As Exception"ERROR ERROR! Can not retrieve images")Finally

DBConn.Close()

 

End Try

 

End Sub

11/09/2008 08:57:49 UTC

MohanKumar
i need to show the saved image in a control like imagebox . how can i do this. can anyone help me?

04/10/2008 02:50:19 UTC

Avinash

Hello Sir
I want to upload an image to server.And this image is assigned to one of the entry in the database which is in Ms Access like if I hav entry in database like MUM-1235  and for this entry if i have image say MUM-1235.gif..
Then when a query is fired to get details about the entry say MUM-1235....at tht time the image should be displayed along with the other fields of an entry.

So I need an asp dot net code in C# to upload and retrieve an image in grid view.

Suggestions are expected

My mail id :

thanks & regards

21/11/2008 02:03:01 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)




Our Ads for you