Don Del Grande
Don Del Grande

Reputation: 429

Generate an <IMG> tag in JavaScript with an array of bytes?

I have an SQL Server table that contains two columns - an integer ID and a varbinary(max) ImageData, which is a JPEG image. In Javascript, I have an Ajax call to get the ImageData for a particular ID and return it as a byte array. How do I generate an XHTML IMG tag that will display the image?

My thought was to use createObjectURL on the returned array, but (a) this needs to be able to run on IE 8, which doesn't seem to support the method, and (b) Firefox appears to be expecting an actual Blob type rather than an array of bytes (and the Blob() constructor doesn't appear to exist).

I do have an alternative - return the data as a Base64 string, then use the tag, but that does not work in IE8, and there may be a size limitation on other browsers (some of the images are 600K, which means that the tag could have over 1 million characters).

Upvotes: 0

Views: 838

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

You are over-engineering a problem where a simpler solution already exists.

Insert the following HTML using AJAX and let the browser fetch the image itself via HTTP. Sending out image data via AJAX would require a pointless base64 encode/decode and ends up taking up more bandwith and defeats the browser cache.

<img src="imageServer.php?imageID=3224" />

Then imageServer.php (you build this or grab it somewhere) will grab the appropriate image record, spit out an image MIME type, then stream the binary data.

Upvotes: 1

Related Questions