Reputation: 558
The project i am working on is basically having a module for comments. Users are able to post and posts are subjected to comments. I have already done most part but am stuck at the part where i need to load all images across all the posts and comments posted.
Each user's profile picture ( thumbnail ) i want to be displayed beside his/her post. The images are stored in the database and NOT file system. I have tried a lot of ways, and none of it seem to work.
here is how i am retrieving the byte array (image data) from the db
TestDBDataContext context1 = new TestDBDataContext();
var r = (from a in context1.ImageTables where a.Id == 8 select a).First();
MemoryStream stream = new MemoryStream(r.FileImage.ToArray());
Method 1: (This does not work, for some reason it shows an invisible image which is having an extension of .aspx.jpeg and it appears corrupt)
an html image tag on the web form
<img src="WebForm1.aspx" alt="" />
code behind
var r = (from a in db.ImageTables where a.Id == 17 select a).FirstOrDefault();
if (r != null)
{
Response.ContentType = "image/jpeg";
Response.BinaryWrite(r.FileImage.ToArray());
return;
}
Method 2 Trying to save the image as System.Drawing.Image object and than linking the image src to that. This way works, but there is no point in having the pics in the database if i cannot retrieve and display multiple images at once.
TestDBDataContext context1 = new TestDBDataContext();
var r = (from a in context1.ImageTables where a.Id == 8 select a).First();
MemoryStream stream = new MemoryStream(r.FileImage.ToArray());
System.Drawing.Image newImage;
newImage = System.Drawing.Image.FromStream(stream);
Random random = new Random();
newImage.Save("D:\\" + random.Next(1000, 5000) + ".jpeg");
I hope you guys are willing to put me on the right track here ! thanks a lot !
Upvotes: 1
Views: 394
Reputation: 6890
Well in our case when we're trying to display image that is being read from the database we usually create a HttpHandler
and set the image like for example:
Logo.ImageUrl = "~/Handlers/GetTempLogo.ashx?LogoGUID=" + Session["TempLogoGUID"];
an in the handler we have:
using (aDataContext db = new aDataContext())
{
var objData = (from c in db.Companies where c.CompanyId == CompanyID select c.LogoSmall).FirstOrDefault();
if (objData == null)
{
context.Response.BinaryWrite(System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/defaultLogo.png")));
return;
}
using (System.IO.MemoryStream str = new System.IO.MemoryStream(objData.ToArray(), true))
{
str.Write(objData.ToArray(), 0, objData.ToArray().Length);
Byte[] bytes = str.ToArray();
context.Response.BinaryWrite(bytes);
}
}
Hope this gives you a hint.
Upvotes: 2