Hamed
Hamed

Reputation: 2168

how to show image from database in asp:image with 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 ?

Upvotes: 6

Views: 12140

Answers (6)

Binod
Binod

Reputation: 457

create ashx page. On it use somthing like this

public void ProcessRequest(HttpContext context)
{

     context.Response.ContentType = "image/jpeg";
     Stream strm = new MemoryStream(GetImage(ID));
     long length = strm.Length;
     byte[] buffer = new byte[length];
     int byteSeq = strm.Read(buffer, 0, 2048);

     while (byteSeq > 0)
     {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 2048);
      }
}
  1. ON get image method

    public static byte[] GetImage(string ImageId)
    {
        byte[] img = null;
    
        DataTable dt = new DataTable();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "USP_SELECT_GLOBAL_METHOD";
        cmd.Parameters.AddWithValue("@EVENT", 5);
        cmd.Parameters.AddWithValue("@CODE", ImageId);
        cmd.Connection = DL_CCommon.Connection();
        SqlDataReader dr = null;
        dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            img = (byte[])dr[0];
        }
        dr.Close();
        return img;
    }
    

    this method return returns the image as ur ID.

  2. on your aspx page..

    Image1.ImageUrl = "somthing.ashx?ID="+userImageID;
    

I hope it will work. as i have found it worked in my own. Thank you

Upvotes: 0

Paul Turner
Paul Turner

Reputation: 39685

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.

Upvotes: 4

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22094

You'll need to create generic handler - lets call it ImageHandler.ashx, and it will be in the root of your web app.

public class ImageHandler : IHttpHandler {
  public void ProcessRequest(HttpContext context) {
    // here is the tricky part - you don't store image type anywhere (you should)
    // assuming jpeg
    context.Response.ContentType = "image/jpeg";

    DataClassesDataContext db = new DataClassesDataContext();
    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null) {
      var thisuser = db.usertables.First(p => p.username == HttpContext.Current.User.Identity.Name);
      if (thisuser != null) {
        byte[] buffer = thisuser.picture.ToArray();
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
      }
    }
  }

  public bool IsReusable {
    get { return false; }
  }
}

Then in the page, add:

<asp:Image runat="server" ImageUrl="~/ImageHandler.ashx" />

Few notes:

you should consider caching of the image

you should switch from image sql type to varbinary (http://msdn.microsoft.com/en-us/library/ms187993.aspx)

you should store image mimetype somewhere (if it is jpeg, png, bmp) - preferably in the same table, and server the correct mimetype in the handler

    -

Upvotes: 4

IvanL
IvanL

Reputation: 2485

You can't render it directly using the ASP.NET Image control (or at least not that I'm immediately aware of). Quickly of the top of my head:

Solution 1: You need some HttpHandler for your images. In your asp:image tag you need an ImageUrl that will be picked up by this specific HttpHandler. There you can write out the image content from the database as bytes using the right MIME type and headers.

Solution 2: Take a look into embedding data in URLs, perhaps you can write out your image like this and add it to the asp:image ImageUrl like that: https://en.wikipedia.org/wiki/Data_URI_scheme

Upvotes: 0

Manish Parmar
Manish Parmar

Reputation: 859

<asp:Image ImageUrl='<%# GetImage(Eval("IMG_DATA")) %>' /> 

Above we tell the ASPX engine that we want to take value of column [IMG_DATA], and pass it into method GetImage of the page, which should return a valid image. So, let's implement the method inside our page class:

public string GetImage(object img)
{
   return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}

Upvotes: 4

nocturns2
nocturns2

Reputation: 661

if thisuser.picture has a proper path to your image, you can try something like this:

Image im = new Image();
im.ID = "myImg";
im.ImageUrl = thisuser.picture.toString();
this.Controls.Add(im);

I am assuming that you are using web forms (I don't think it makes a difference).

Also, this might require a page refresh. The 'this' is referring to the Page object (in my case).

Upvotes: 0

Related Questions