3

I want to retrieve an image from database and then send it to view and display it as thumbnail. Here is my code but It has some error and I can't return the image properly. I'm using ASP.Net MVC and aspx pages.

Controller :

public ActionResult showImg(int id)
{
   var imageData = from m in db.Products
                   where m.ShopId == 3
                   select Image.FromStream(new MemoryStream(m.Product_img.ToArray()));

   return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}

View :

<img src='<%= Url.Action("showImg", "image", new { id = ViewData["imageID"] } ) %>' /> 
4
  • Have you ruled out any database issue, just trying to return a hardcoded filename instead of a memory stream? Commented Nov 2, 2012 at 10:10
  • No it is just a test. I won't use hardcode in real situation. Commented Nov 2, 2012 at 10:13
  • I know you will not want to hardcode it - but are you sure that it is not a database connection issue? And is your query returning exactly what you want? Commented Nov 2, 2012 at 10:16
  • Yes my friend, I have already inserted an image to the table successfully, but now I want to retrieve it. The imageData filled with System.Drawing.Image but FileStreamResult wants to return (byte[],string). Thats it. Commented Nov 2, 2012 at 10:26

2 Answers 2

5

It looks like you do not need to recreate the Image object in your linq statement, just return the stream and pass it your FileStreamResult:

var image = (from m in db.Products
             where m.ShopId == 3
             select m.Product_img).FirstOrDefault();

var stream = new MemoryStream(image.ToArray());

return new FileStreamResult(stream, "image/jpeg");
Sign up to request clarification or add additional context in comments.

3 Comments

Cannot convert System.Linq.IQueryable<System.IO.MemoryStrem> to System.IO.Stream
Only parameterless constructors and initializers are supported in LINQ to Entities.
Have updated the answer again, now performing MemoryStream construction outside of the linq statement.
0

Thanks a lot Nick. Your code is now correct. I wrote it in this way :

    var stream = (from m in db.Products where m.ShopId == 3 select m.Product_img).FirstOrDefault();

            return File(stream, "image/jpeg");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.