Click here to Skip to main content
Click here to Skip to main content

Previewing Image in ASP.NET Image Control using C#

By , 7 Aug 2012
 

Introduction

Recently there are so many people asking in forums how to preview an uploaded image before saving it to the database. In this article, let us see how to preview an uploaded image in ASP.NET before saving it to database. Also this we will see how to feed a byte array into an image control. We are going to achieve this using an IhttpHandler.

Using the code

  1. Create a new website. Add a FileUpload control, a button, and an image control.
  2. ASPX code:

    <table>
        <tr>
            <td class="style3">
                <asp:Label ID="Label1" runat="server" Text="Photo upload" />
            </td>
            <td class="style4">
                <asp:FileUpload runat="server" ID="PhotoUpload" />
            </td>
            <td class="style4">
                <asp:Button runat="server" ID="btnPhotoPreview" Text="Preview" />
            </td>
            <td class="style1">
                <asp:Image runat="server" ID="ImagePreview" Height="164px" Width="125px" />
            </td>
        </tr>
    </table>
  3. Now add a button click event for “btnPhotopreview”.
  4. <asp:Button runat="server" OnClick="btnPreview_Click" ID="btnPhotoPreview" Text="Preview" />
  5. We have to add a handler class in order to show the image. We are going to pass the session variable for FileBytes for the upload control. In the new handler class, get the session variable and generate the image.
  6. When we add the .ashx file, it will have some code inside it.

    <%@ WebHandler Language="C#" Class="ImageHandler" %>
    
    using System;
    using System.Web;
    
    public class ImageHandler : IHttpHandler {
        
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }
    }

    Just rewrite the code inside processrequest to get the session variable and generate the image.

    In order to use the session variable in the HTTPHandler class we also implement our class from IRequiresSessionState.

    <%@ WebHandler Language="C#" Class="ImageHandler" %>
    
    using System;
    using System.Web;
    
    public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        
        public void ProcessRequest (HttpContext context) {
           //Checking whether the imagebytes session variable have anything else not doing anything
    
            if ((context.Session["ImageBytes"]) != null)
            {
                byte[] image = (byte[])(context.Session["ImageBytes"]);
                context.Response.ContentType = "image/JPEG";
                context.Response.BinaryWrite(image);
            }
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }
    }
  7. Now inside the button click in our page, get the file bytes from the FileUpload control and save it in the session variable.
  8. protected void btnPreview_Click(object sender, EventArgs e)
    {
        Session["ImageBytes"] = PhotoUpload.FileBytes;
        ImagePreview.ImageUrl = "~/ImageHandler.ashx";
    }

Now run the application and browse the image and preview it.

I have attached the complete source code also.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Santhosh Kumar Jayaraman
Software Developer EF
India India
Member
Started my career with Infosys and currently working with Education First. I have great passion towards Microsoft technologies. I have experience in Microsoft technologies like WPF, WCF, ASPNET, WinForms,Silverlight, VB.NET, C-Sharp Entity framework,SSRS, LINQ, Extension methods and SQL server.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionMultiple images in the same pagememberMember 21609874 Apr '13 - 0:09 
Hi,
thanks for sample, is very good.
I've implemented it and works very well.
 
But now I have another issue, in the same page I have 9 image controls and I'm trying to load them as described, but... all controls show the same image even if I've saved in different session variables:
Session("Image1"), Session("Image2")....
and I've modified the ProcessRequest:
 
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
 
Try
 
For i As Integer = 1 To 9
If (context.Session("Image" & i)) IsNot Nothing Then
Dim image As Byte() = DirectCast(context.Session("Image" & i), Byte())
context.Response.ContentType = "image/JPEG"
context.Response.BinaryWrite(image)
End If
 
Next
 
Catch ex As Exception
 
End Try
 

End Sub
 
What do I have to do to load more Imgage controls with different images?
GeneralMy vote of 5memberabhi99314 Mar '13 - 8:41 
this is what i wanted
GeneralMy vote of 4memberZan Zan Koe23 Dec '12 - 6:00 
This article is useful for me. Thanks xo much... Smile | :)
GeneralThanksmemberMember 954329825 Oct '12 - 9:59 
Thanks, really helped. Big Grin | :-D
Questionif Session["ImageBytes"] returns nullmemberPritesh Aryan12 Oct '12 - 5:08 
what to do if
Session["ImageBytes"]
return null?
or how to check if session of image byte is ?
AnswerRe: if Session["ImageBytes"] returns nullmemberSanthosh Kumar J12 Oct '12 - 6:13 
we are loading only session is not null.if it is null, nothing will be displayed. see this condition
in ImageHandler class
if ((context.Session["ImageBytes"]) != null)
        {
            byte[] image = (byte[])(context.Session["ImageBytes"]);
            context.Response.ContentType = "image/JPEG";
            context.Response.BinaryWrite(image);
        }

QuestionThank!membergoomingi11 Oct '12 - 18:58 
^^ Thank you so much! That's a useful post! Big Grin | :-D
Cám ơn tác giả rất nhiều ạ! ^^
AnswerRe: Thank!memberSanthosh Kumar J11 Oct '12 - 18:59 
welcome
GeneralMy vote of 4membergoomingi11 Oct '12 - 18:56 
Thank you very much! Big Grin | :-D
Questionpreview after choosing filememberMember 944104918 Sep '12 - 23:50 
Can we see the image without hitting the button Preview?
AnswerRe: preview after choosing filememberSanthosh Kumar J19 Sep '12 - 2:05 
Yes, But that need to be done differently. Here i just made to display preview only if user clicks on button
GeneralRe: preview after choosing filememberMember 445948429 Oct '12 - 8:43 
can you please help me with showing image without clicking preview?
AnswerRe: preview after choosing filememberSridhar Ch31 Oct '12 - 23:32 
add this JS method
function ShowPreview() {
            var btn = document.getElementById("btnPreview");
            btn.click();
        }
 
Place preview button in a div with style display none.
<asp:FileUpload ID="FileUpload1" runat="server" onchange="ShowPreview()"  />
        <div style="display: none">
            <asp:Button ID="btnPreview" runat="server" OnClick="btnPreview_Click" />
        </div>

GeneralRe: preview after choosing filememberyugandhar1126 Feb '13 - 23:13 
Thank u so much, i got the solution....
GeneralMy vote of 4memberTathagat Verma7 Aug '12 - 19:00 
The solution is good. Though a little more explanation would've been better.
GeneralImage uploadmembershanid3602 Aug '12 - 20:37 
Hai friends Smile | :)
The uploading of the image file is performed by ASP.NET 4.0 Client Callbacks. If you are not familiar with client callbacks then I suggest that you take a look at ASP.Net AJAX Control Toolkit AsyncFileUpload Control without page refresh or PostBack in ASP.Net Web Page or ASP.Net AJAX Update Panel. The callback is fired as soon as the file is selected by the user using the file field control.
Thanks % Regards
Shanith Thekkayil
Image Upload Thumbs Up | :thumbsup:
GeneralMy vote of 5memberCarsten V2.029 Jul '12 - 5:02 
Superb! Smile | :)
GeneralRe: My vote of 5memberSanthosh Kumar J6 Aug '12 - 2:50 
Thanks.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 7 Aug 2012
Article Copyright 2012 by Santhosh Kumar Jayaraman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid