Convert and save Byte Array as Image in ASP.Net using C#

Convert and save Byte Array as Image in ASP.Net using C#


Display byte array i.e. Binary Data as Image on the web page in ASP.Net Image Control without using a Generic Handler to render the image.

Note:

First off all, you have to create a folder and assign its name as Files.Here only uploaded image will be saved.

Source code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click" />
<hr />
<asp:Image ID="Image1" Visible = "false" runat="server" Height = "100" Width = "100" />

    </div>
    </form>
</body>
</html>

c# code

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace test1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            Stream fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            byte[] bytes = br.ReadBytes((Int32)fs.Length);

            //Save the Byte Array as File.
            string filePath = "~/Files/" + Path.GetFileName(FileUpload1.FileName);
            File.WriteAllBytes(Server.MapPath(filePath), bytes);

            //Display the Image File.
            Image1.ImageUrl = filePath;
            Image1.Visible = true;

        }
    }

}


Output


Fig(1)Now run your application and select an image from your device to upload and display on your screen.At the same time uploaded image will be saved in specified folder

Thanks for visiting....

Share this

Related Posts

Previous
Next Post »