1

i stored few images in database in binary format, now i want to display those images in my view,how can we convert those images from binary format to image format again?

this is my action menthod in my controller

           public ActionResult DislpayAllImage()
           {
            DataSet dsa = new DataSet();
            dsa = objImage.getAllImages();
            DataTable dt = new DataTable();
            dt = dsa.Tables[0];
            if (dt != null)
            {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Byte[] image = (Byte[])dt.Rows[i]["UsImage"];
                return File(image, "image/jpg");
             }
            }
        return View();



    }

this is my code in model

     public DataSet getUserImage(int Id)
     {
        DataSet ds = new DataSet();
        try
        {
            DbCommand db = dbcon.GetStoredProcCommand("GetImage");
            dbcon.AddInParameter(db, "@Id", DbType.Int16, Id);
            db.CommandType = CommandType.StoredProcedure;
            return ds = dbconstr.ExecuteDataSet(dbCmd);
        }
        catch(Exception ex)
        {
            return ds = null;
        }
    }

view

 @foreach( var image in ViewData.Images )
 {
  <img src="@Url.Action("DislpayImage", "Home",new { id = image.ImageID })" />
 }

how can i display my image in razor view,also is the above code fine?

colors bright
  • 107
  • 1
  • 3
  • 18

2 Answers2

2

You need to call your Controller's Action(DislpayImage()) from the View like this:

<img src="<%= Url.Action("DislpayImage", "Controller") %>" alt="myimage" />

or

<img src="@Url.Action("DislpayImage", "Controller")" alt="myimage" />

Hope it helps you.


Edit

Just pass the id of the image you want to display to Controller action

public ActionResult DislpayImage(int id)
     {
        DataSet dsa = new DataSet();

        dsa = objImage.getUserImage(id);
        var imagedata = dsa.Tables[0].Columns["MyImage"];
        return File(imagedata, "image/jpg");

     }

Now pass the id of image which you want to display in your view, like this:

<img src="@Url.Action("DislpayImage", "Controller", new { id="2" })" alt="myimage" />

Now you will get the image with id as 2.

Karthik Chintala
  • 5,465
  • 5
  • 30
  • 60
0
<% foreach( var image in ViewData.Images ) { %> 
  <%= Html.Image( Url.Action( "Show", "Image", new { id = image.ImageID } ) ) %> 
<% } %>



 public class ImageController : Controller

    {

        public void Show(string id)

        {

           Image image = GetImage(id);


           Response.Buffer = True;
           Response.Clear();
           Response.ContentType = "image/gif";
           Response.BinaryWrite( image.Data );
           Response.End();

       }

    }

This response is just a copy of an answer from another forum. This is not my own. I'm pasting it here to help you and someone else in this forum with the same issue.

Here is the main link: http://forums.asp.net/post/2264885.aspx