Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
i am using this code for retriving image from sql to asp.

But i am unble to show it into Image control provided by asp.net

i am sure this code is usefull for window application

How can i show image for asp
please suggest for asp.
C#
TextBox Name1 = LoginUser.FindControl("UserName") as TextBox;
String Name = Name1.Text;
TextBox pass = LoginUser.FindControl("Password") as TextBox;
String pass2 = pass.Text;
SqlCommand cmd = new SqlCommand("Select * from UserInfo where UserName1 = '" + Name + "' And Password1 = '" + pass2 + "'", conn);
conn.Open();
dr = cmd.ExecuteReader();

if (dr.HasRows)
{            dr.Read();
    byte[] b = (byte[])dr[3];
    MemoryStream ms = new MemoryStream(b);
    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
Posted
v6

Code on the .ASPX page :
XML
<img runat=server id="logoImg" alt="" src="" />

C# Code behind it :
C#
byte[] imgArray =  (byte[])dTable.Rows[0][8];
logoImg.Src = "data:image/png;base64," + Convert.ToBase64String(imgArray);
 
Share this answer
 
Comments
Ashwani Gusain 25-Sep-13 5:07am    
thanks sir for your usefull answer but sir it showing one error pls check it

'System.Web.UI.WebControls.Image' does not contain a definition for 'Src' and no extension method 'Src' accepting a first argument of type 'System.Web.UI.WebControls.Image' could be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\ashwani.g\My Documents\Visual Studio 2010\WebSites\Fussionbook\Account\Login.aspx.cs 44 21 C:\...\Fussionbook\
Rick van Woudenberg 25-Sep-13 5:44am    
See my solution (solution 3 )
Wiliam Ferraciolli 12-Apr-14 19:15pm    
Very good mate, nice one
mohamadMahmodi 3-Apr-15 15:49pm    
hey tanks, it's worked but i wana know what's "data:image/png;base64" and "ToBase64String(imgArray)" for?
C#
//I am not a byte a array so  i am selecting an image from openfiledialogbox and converting it to byte[].
openFileDialog1.ShowDialog();
Image img = Image.FromFile(openFileDialog1.FileName);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bt = ms.ToArray();
//till now i had converted my image in to byte[].
//now from this byte[] i am creating a Image

MemoryStream ms2 = new MemoryStream(bt);
System.Drawing.Image img2 = System.Drawing.Image.FromStream(ms2);
//i got my image.

Bitmap bit = new Bitmap(200, 200);
Graphics g = Graphics.FromImage(bit);
g.DrawImage(img2, new Point(0, 0));
bit.Save("abc.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("Done");
yourImageControl.ImageUrl = "Images/abc.jpg";
//just replace the path "abc.jpg" in your code with "Server.MapPath("Images/abc.jpg")"
 
Share this answer
 
v2
Comments
Ashwani Gusain 26-Sep-13 8:26am    
dear sir same error is coming again.
May i clear you this for web application not for window application.
Ashwani Gusain 27-Sep-13 3:11am    
Dear sir any Updates.
Er Daljeet Singh 30-Sep-13 5:18am    
Yes i know its a web application.
May be you are getting this error because of your Byte Array.Check the image you are storing in you database is correct or not.Actually i don't have image in database that's why i used window app to easily convert it into byte array.Just check you byte array run the code again,That code is working fine scenario.
You can check in this link where i have created a captcha,
http://rmedutech.com/Account/Register#7343bb738cce4be0b3d37935db527572
Ashwani Gusain 30-Sep-13 5:53am    
dear sir i am storing image in bitbinary datatype in sql this application for working for windows application but we can't convert it on web application here we dont't have picturebox which convert directaly bit to image that why i am facing this problems first we have to store this bits into our webpage then only it will.

if i am worng please correct me
Er Daljeet Singh 30-Sep-13 8:05am    
No we don't need to convert a bit array or byte array for web application.IF your bit array stored in db is correct then you just need to create a image fro that bit array that's sit.nothing else.
Here is the solution,

Default.aspx.cs

using System.IO;
using System.Drawing;
//For inserting image in to database.
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("Images/abc.jpg"));
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] bt = ms.ToArray();
            ViewState["byteArray"] = bt;
        }
    }
    //For Fetching image from database
    protected void Button2_Click(object sender, EventArgs e)
    {
        byte[] bt = ViewState["byteArray"] as byte[];
        MemoryStream ms2 = new MemoryStream(bt);
        System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms2);
        Bitmap bit = new Bitmap(ms2, true);
        bit.Save(Server.MapPath("Images/abc.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
        Image1.ImageUrl = "Images/abc.jpg";
    }



Code for Default.aspx

XML
<form id="form1" runat="server">

   <asp:FileUpload ID="FileUpload1" runat="server" />
   <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />
   <br />
   <asp:Image ID="Image1" runat="server"  Height="200px" Width="200px"/>
   <asp:Button ID="Button2" runat="server" Text="Fetch Image"
       onclick="Button2_Click" />

   </form>
 
Share this answer
 
Comments
Ashwani Gusain 30-Sep-13 9:50am    
dear sir one confusion is there

System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("Images/abc.jpg"));

this line will take the file from the given path but this path will be different

like i am using

String BO = System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(BO));

BUT this taking virtual path not physical path
but i need to take file from local machine and show it
Always improve your answer, don't post multiple answers. Please delete this and add all these inside the first solution given by you.

Thanks,
Tadit
You need to implement Genric Handler. Here are some examples

How to store and retrieve images from SQL server database using asp.net?[^]
Display image from database in ASP.net with C#[^]


[Edit member="Tadit"]
Link text added to reflect the article title.
[/Edit]
 
Share this answer
 
v2
Comments
Member 12807020 9-Nov-16 1:29am    
getting error Non-invocable member 'File' cannot be used like a method.
on this line return File(ms.ToArray(), "image/png");using in webapi
I made a mistake in my initial solution. WebControls.Image is just a HTML container for an image URL - you can't store the image data directly in it, you just store the reference (URL) to an image file. If you need to retrieve image data dynamically, the usual approach is to create an image handler that will handle the request and return the image as a stream that the browser can display. You can create ASPX page that will return image file as byte array with appropriate headers information, to get image you will be able to call this page like imagemanager.aspx?imgid=31337

Then in your main page in system.web.ui.webcontrols.image control set ImageUrl property to your script path:

C#
ctrlImage.ImageUrl = "imagemanager.aspx?imgid=31337";

Here is example of method to output you image in imagemanager.aspx:
C#
private void TransmitBytes(byte[] bytes, string outFileName)
{
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + outFileName);
    Response.AddHeader("Content-Length", bytes.Length.ToString());
    Response.ContentType = "image/jpeg";
    Response.BinaryWrite(bytes);
    Response.End();
}


This should work :)


[Edit member="Tadit"]
Corrected formatting issues.
[/Edit]
 
Share this answer
 
v2
Comments
Always improve your answer, don't post multiple answers. Please delete this and add all these inside the first solution given by you.

Thanks,
Tadit
This is code you had posted i am justion adding 2-3 line as solution to this question.


TextBox Name1 = LoginUser.FindControl("UserName") as TextBox;
String Name = Name1.Text;
TextBox pass = LoginUser.FindControl("Password") as TextBox;
String pass2 = pass.Text;
SqlCommand cmd = new SqlCommand("Select * from UserInfo where UserName1 = '" + Name + "' And Password1 = '" + pass2 + "'", conn);
conn.Open();<pre></pre>
dr = cmd.ExecuteReader();
if (dr.HasRows)
{ dr.Read();
byte[] b = (byte[])dr[3];
MemoryStream ms = new MemoryStream(b);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

Bitmap bit = new Bitmap(200,200);

Graphics g = Graphics.FromImage(img);
g.DrawImage(img,new Point(0,0));

bit.Save(Server.MapPath("Images/abc.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
yourImageControl.ImageUrl = "Images/abc.jpg";


this is how it done.actually you are reading a byte[] from database so create image from this byte array and store that image in some location and give that location to you image contorl.
second option is use Image handler mean create a handler that will display image.
second one i think is complex.
 
Share this answer
 
v2
Comments
Er Daljeet Singh 26-Sep-13 3:53am    
I have modified the code.Please check it again and tell us whether it is working or not
Er Daljeet Singh 26-Sep-13 6:04am    
I am going to post code again
Er Daljeet Singh 30-Sep-13 8:31am    
I am going to post the code which in working fine in web application.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900