Click here to Skip to main content
15,867,834 members
Articles / Web Development / ASP.NET
Tip/Trick

Previewing Image in ASP.NET Image Control using C#

Rate me:
Please Sign up or sign in to vote.
4.50/5 (16 votes)
7 Aug 2012CPOL1 min read 171.4K   6.9K   15   22
Previewing Image in ASP.NET Image Control using C#

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:

    XML
    <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.NET
    <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. Image 1

    When we add the .ashx file, it will have some code inside it.

    C#
    <%@ 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.

    C#
    <%@ 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. C#
    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.

Image 2

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)


Written By
Technical Lead EF (Education First)
India India
I graduated as Production Engineer and started my career as Software Developer then worked as tester for a while before moving into Windows application development using Microsoft Technologies. But for the last few years i am working on javascript, React, Node, AWS, Azure Chatbots

Comments and Discussions

 
Questionon image Pin
Member 1035139617-Mar-16 6:54
Member 1035139617-Mar-16 6:54 
Questionnot working on vs 2015 Pin
Member 1035139617-Mar-16 6:48
Member 1035139617-Mar-16 6:48 
QuestionMultple Images Pin
Member 1050351423-Mar-15 3:55
Member 1050351423-Mar-15 3:55 
GeneralMy vote of 3 Pin
Mohammad Alghanem27-Jan-15 2:44
professionalMohammad Alghanem27-Jan-15 2:44 
QuestionMultiple images in the same page Pin
Member 21609874-Apr-13 0:09
Member 21609874-Apr-13 0:09 
GeneralMy vote of 5 Pin
abhi99314-Mar-13 8:41
abhi99314-Mar-13 8:41 
GeneralMy vote of 4 Pin
Zan Zan Koe23-Dec-12 6:00
Zan Zan Koe23-Dec-12 6:00 
GeneralThanks Pin
Member 954329825-Oct-12 9:59
Member 954329825-Oct-12 9:59 
Questionif Session["ImageBytes"] returns null Pin
Pritesh Aryan12-Oct-12 5:08
Pritesh Aryan12-Oct-12 5:08 
AnswerRe: if Session["ImageBytes"] returns null Pin
Santhosh Kumar Jayaraman12-Oct-12 6:13
Santhosh Kumar Jayaraman12-Oct-12 6:13 
QuestionThank! Pin
goomingi11-Oct-12 18:58
goomingi11-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! Pin
Santhosh Kumar Jayaraman11-Oct-12 18:59
Santhosh Kumar Jayaraman11-Oct-12 18:59 
GeneralMy vote of 4 Pin
goomingi11-Oct-12 18:56
goomingi11-Oct-12 18:56 
Questionpreview after choosing file Pin
Member 944104918-Sep-12 23:50
Member 944104918-Sep-12 23:50 
AnswerRe: preview after choosing file Pin
Santhosh Kumar Jayaraman19-Sep-12 2:05
Santhosh Kumar Jayaraman19-Sep-12 2:05 
GeneralRe: preview after choosing file Pin
Member 445948429-Oct-12 8:43
Member 445948429-Oct-12 8:43 
AnswerRe: preview after choosing file Pin
Srinivasa Sridhar31-Oct-12 23:32
Srinivasa Sridhar31-Oct-12 23:32 
GeneralRe: preview after choosing file Pin
yugandhar1126-Feb-13 23:13
yugandhar1126-Feb-13 23:13 
GeneralMy vote of 4 Pin
Tathagat Verma7-Aug-12 19:00
Tathagat Verma7-Aug-12 19:00 
GeneralImage upload Pin
shanid3602-Aug-12 20:37
shanid3602-Aug-12 20:37 
GeneralMy vote of 5 Pin
Carsten V2.029-Jul-12 5:02
Carsten V2.029-Jul-12 5:02 
GeneralRe: My vote of 5 Pin
Santhosh Kumar Jayaraman6-Aug-12 2:50
Santhosh Kumar Jayaraman6-Aug-12 2:50 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.