Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Display Byte Array as Image without using Generic Handler in Asp.net in C#, VB.NET

Aug 24, 2015
Introduction

Here I will explain how to show or display byte array as image from database in image control without using generic handler ashx in
 asp.net using c#, vb.net with example or upload images in byte array format and display images from sql server database  in image control without using generic handler ashx in asp.net gridview using c#, vb.net.


To display byte array image in image control we need to write the code like as shown below


<asp:Image ID="Image1" runat="server" ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("imagedata")) %>'  Height="150px" Width="150px"/>


if you want to check it in complete example first design one table imagedetails in your database as shown below

Column Name
Data Type
Allow Nulls
imageid
Int(IDENTITY=TRUE)
NO
imagename
varchar(50)
Yes
imagedata
varbinary(max)
Yes
Once table created in database that would be like as shown below


Now open your aspx page and write the code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title>Display images from sql server database in asp.net gridview control</title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
.headerstyle
{
color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;background-color: #df5015;padding:0.5em 0.5em 0.5em 0.5em;text-align:center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</div>
<div class="GridviewDiv">
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False">
<HeaderStyle CssClass="headerstyle" />
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("imagedata")) %>'  Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

Now add following namespaces in codebehind file

C# Code


using System;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
using System.Web;

After completion of adding namespaces you need to write the code like as shown below


string strCon = "Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
// Bind Gridview Data
private void BindGridviewData()
{
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select imageid,imagename,imagedata from imagedetails";
cmd.Connection = con;
con.Open();
gvImages.DataSource = cmd.ExecuteReader();
gvImages.DataBind();
con.Close();
}
}
}
// Save files to Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileUpload1.HasFile)
{
int length = fileUpload1.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileUpload1.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length); 
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into imagedetails(imagename,imagedata) values(@Name,@Data)";
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@Data", imgbyte);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
}
}
}

VB.NET Code


Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls
Imports System.Web
Partial Class VBCode
Inherits System.Web.UI.Page
Private strCon As String = "Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub
' Bind Gridview Data
Private Sub BindGridviewData()
Using con As New SqlConnection(strCon)
Using cmd As New SqlCommand()
cmd.CommandText = "select imageid,imagename,imagedata from imagedetails"
cmd.Connection = con
con.Open()
gvImages.DataSource = cmd.ExecuteReader()
gvImages.DataBind()
con.Close()
End Using
End Using
End Sub
' Save files to Folder and files path in database
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
'Condition to check if the file uploaded or not
If fileUpload1.HasFile Then
Dim length As Integer = fileUpload1.PostedFile.ContentLength
Dim imgbyte As Byte() = New Byte(length - 1) {}
Dim img As HttpPostedFile = fileUpload1.PostedFile
'set the binary data
img.InputStream.Read(imgbyte, 0, length)
Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName) 
Using con As New SqlConnection(strCon)
Using cmd As New SqlCommand()
cmd.CommandText = "insert into imagedetails(imagename,imagedata) values(@Name,@Data)"
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@Data", imgbyte)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
BindGridviewData()
End Using
End Using
End If
End Sub
End Class

oNow run your application and check output that would be like as shown in following output

Demo

Display Byte Array as Image without using Generic Handler in Asp.net in C#, VB.NET

Download Sample Code Attached


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

0 comments :

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.