How to retrieve images from SQL Database using C#?
-
3Google "Display Blob Image C#"ta.speot.is– ta.speot.is2011-03-31 09:47:34 +00:00Commented Mar 31, 2011 at 9:47
-
What's your approach? Why doesn't it work (Exception message, compiler error...)?Daniel Hilgarth– Daniel Hilgarth2011-03-31 09:48:15 +00:00Commented Mar 31, 2011 at 9:48
-
Go ahead,give it a try first, comeback here if you're stuck somewhere!painotpi– painotpi2011-03-31 09:51:57 +00:00Commented Mar 31, 2011 at 9:51
-
Bare in mind sql stores an image as a blob, which is essentially a byte array. Try and look for examples on converting a byte array to a c# Image object.firefox1986– firefox19862011-03-31 09:55:03 +00:00Commented Mar 31, 2011 at 9:55
-
SO won't let me answer with a let me google that for you but if you use your exact question as a google search you get your answer.BenCr– BenCr2011-03-31 09:56:41 +00:00Commented Mar 31, 2011 at 9:56
Add a comment
|
2 Answers
I believe this is what you need: an msdn example with code! it should at least get you started.
Comments
Why dont you try by using query string . Here is my code where in query string is used and i fetch images from the database without having to create the any instatnce of that desired image inyour local folder. Hop this helps.
<%@ WebHandler Language="C#" Class="DisplayImg" %>
using System;
using System.Web;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class DisplayImg : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string theID;
if (context.Request.QueryString["id"] != null)
theID = context.Request.QueryString["id"].ToString();
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = DisplayImage(theID);
byte[] buffer = new byte[2048];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
public Stream DisplayImage(string theID)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString());
string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", theID);
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Just add one line in CS code
UploadImg.ImageUrl = "~/DisplayImg.ashx?id=" + code;
1 Comment
avishayp
-1 for not using
using, not null checking, and returning a stream from the method.