Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC - Display series of images based on byte[]

Tags:

asp.net-mvc

I want to display a list of images and a description on a webpage using ASP.net MVC. The images are stored in a SQL Server DB and i'm getting them back as a byte[].

However, I don't understand how I can display a series of images on a page. I want to do something like this:

<% foreach(Product p in Model.Products)
      Response.Write(p.Description)
      Response.Write(html.Image(p.ImageArray)
%>

But the only code I've saw has been displaying a single image...

Thank you

Ben

like image 562
Ben Hall Avatar asked Dec 03 '25 22:12

Ben Hall


2 Answers

Rather than creating a new HttpHandler you can just write a controller action that returns the contents of the image file. Then add images to the page with their src attribute set to the action you created.

EDIT: Note that streaming images as byte[] from a database is inefficient compared to serving static files.

like image 140
liammclennan Avatar answered Dec 05 '25 10:12

liammclennan


You will need to create a custom IHttpHandler that will serve the images something like this:

    public class AlbumArt : IHttpHandler
        {
            public void ProcessRequest(HttpContext Context)
            {
byte [] b = your image...;
    Context.Response.ContentType = "image/jpeg";
                        Context.Response.BinaryWrite(b);
    }
    }

And then you would need to retrieve each image from there by using image tags in your html, something like

<img src="AlbumArt.ashx?imageId=1" />
like image 32
Nick Avatar answered Dec 05 '25 11:12

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!