TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Convert from binary data to an image control in ASP.NET
Ajeet Kumar
Jul 14
2016
Code
11.1
k
0
1
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
CS.aspx
<
form
id
=
"form1"
runat
=
"server"
>
<
asp:DropDownList
ID
=
"ddlImages"
runat
=
"server"
AppendDataBoundItems
=
"true"
AutoPostBack
=
"true"
OnSelectedIndexChanged
=
"FetchImage"
>
<
asp:ListItem
Text
=
"Select Image"
Value
=
"0"
/>
</
asp:DropDownList
>
<
hr
/>
<
asp:Image
ID
=
"Image1"
runat
=
"server"
Visible
=
"false"
/>
</
form
>
CS.aspx.cs
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(!
this
.IsPostBack)
{
ddlImages.DataSource = GetData(
"SP_Producto"
);
ddlImages.DataTextField =
"ProductoNombre"
;
ddlImages.DataValueField =
"ProductoId"
;
ddlImages.DataBind();
}
}
private
DataTable GetData(
string
query)
{
DataTable dt =
new
DataTable();
using
(SqlConnection con =
new
SqlConnection(@
"Data Source=DataSourceName;Initial Catalog=CalalogName;User ID=sa ; password=*******"
))
{
using
(SqlCommand cmd =
new
SqlCommand(query))
{
using
(SqlDataAdapter sda =
new
SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return
dt;
}
}
protected
void
FetchImage(
object
sender, EventArgs e)
{
string
id = ddlImages.SelectedItem.Value;
Image1.Visible = id !=
"0"
;
if
(id !=
"0"
)
{
byte
[] bytes = (
byte
[])GetData(
"SELECT ProductoImagen FROM Producto WHERE ProductoId ="
+ id).Rows[0][
"ProductoImagen"
];
string
base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl =
"data:image/png;base64,"
+ base64String;
}
}
private
System.Drawing.Image BinaryToImage(
byte
[] b)
{
if
(b ==
null
)
return
null
;
using
(MemoryStream ms =
new
MemoryStream(b, 0, b.Length))
{
ms.Write(b, 0, b.Length);
System.Drawing.Image newImage = System.Drawing.Image.FromStream(ms);
return
newImage;
}
}
Convert from binary data to an image control in ASP.NET