Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting a byte arrain into the src attribute of an img tag

Tags:

asp.net-mvc

I'm using ASP.NET MVC and have a model which has an image (byte array) in one of the fields. I'm trying to output this image into the src attribute of the img tag. I'm looking to do something like <img src='<%= Model.VenueImage %>'>. How can I do this?

like image 940
Webcognoscere Avatar asked Apr 15 '10 10:04

Webcognoscere


People also ask

How do I display an image in a byte array?

The selected Image file is first converted to Byte Array and then displayed in PictureBox control using the FromStream function of the Image class.

What is the src attribute of an IMG tag for?

The <img> tag has two required attributes: src - Specifies the path to the image. alt - Specifies an alternate text for the image, if the image for some reason cannot be displayed.

How do I give an image an src?

To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.

What is byte image?

Images are binary data - this is easily represented as byte arrays. The image in the sample is stored in the database as a BLOB - not a string or location, that is, it is binary data.


1 Answers

Maybe Inline Images with Data URLs idea?

Inline images use the data URI scheme to embed images directly within web pages. As defined by RFC 2397, data URIs are designed to embed small data items as "immediate" data, as if they were referenced externally. Using inline images saves HTTP requests over externally referenced objects.

System.Drawing.Image image = GetImageFromSomewhere(...);

byte[] imageData = ImageToByteArray(image);
string imageBase64 = Convert.ToBase64String(imageData);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);

and then somewhere in the page:

<img src= "<%= ImageSrcBytes %>" />

AFAIK this will work for Opera 7.2+, Firefox, Safari, Netscape, Mozilla and IE8+ (IE8 up to 32kb).

For earlier version of IE there is a workaround - MHTML.

The example how to do it is here.

like image 53
Oleks Avatar answered Feb 02 '23 19:02

Oleks