Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show image from database in asp:image with linq?

Tags:

asp.net

linq

This is my table in database :

enter image description here

And I read the database like :

DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);

So, thisuser.picture is a handle to the image. But how can I show it in asp:image control on my page ?

Edit I save the picture with this code :

DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
byte[] filebyte = FileUpload1.FileBytes;
System.Data.Linq.Binary fileBinary = new System.Data.Linq.Binary(filebyte);
thisuser.picture = fileBinary;
db.SubmitChanges();

is there something wrong ?

like image 866
Hamed Avatar asked Dec 16 '22 09:12

Hamed


1 Answers

The ASP.NET Image control loosely represents an <img> tag in HTML. As a result you can only get an image into an HTML doocument by setting the URL to the image content you want to embed in the page.

<img src="images/picture.png" />

This means that you need a mechanism to take an HTTP request asking for an image resource, and return a response containing the image binary data.

With ASP.NET Web API this becomes a trivial operation to implement:

public HttpResponseMessage GetImage(string username)
{
    DataClassesDataContext db = new DataClassesDataContext();
    usertable thisuser = db.usertables.FirstOrDefault(
        p => p.username == username);

    if (thisuser == null)
    {
        return new HttpResponseMessage(HttpStatusCode.NotFound)); 
    }

    // Create a stream to return to the user.
    var stream = new MemoryStream(thisuser.picture.ToArray());

    // Compose a response containing the image and return to the user.
    var result = new HttpResponseMessage();

    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
            new MediaTypeHeaderValue("image/jpeg");

    return result;
}

If you can't use Web API, you'll have to implement an HTTP Handler to do the same job.

In your ASP.NET page, you will have to set the property ImageUrl to the address configured for your controller/handler, including the username as part of the URL.

like image 120
Paul Turner Avatar answered Feb 04 '23 18:02

Paul Turner