I am currently reading an image from an SQL Server database as byte[]. I would like to pass the image either as a byte[] or a real image to jQuery and dynamically load it.
How and what would be the best approach to do this?
Thanks in advance. :)
Edit: Here's the solution:
string json = JsonConvert.SerializeObject(employee);
$('#image').attr('src', "data:image/jpg;base64,"+employee.Image);
Return the byte[] from the webserver with the correct content-type set, that way you should be able to set it as a source for a image tag. Should be the simplest solution.
If you must do it this way, you can insert image data directly into the src attribute using the following syntax:
data:image/<type>;base64,<data>
Replace with the image type (jpg, png, gif) and with your data, encoded in base 64.
However, as decyclone says, the best way to do this would be to create a separate page that only outputs your image data, and sends the appropriate content-type header. Then set the image src to point to that page.
I don't think using jQuery is the right thing to do here. It's a client side thing. JavaScript, to be specific.
Usually, you create a page that writes all these bytes in array using Response.Write()
and setting the content-type to jpeg, bmp, etc. depending on image type.
I am currently reading an image from a JSON
Response. I would like to pass this encoded string into the image control on Jquery
template and load it dynamically, How and what would be the best approach to do this? Template is as follows:
<script id="ImageDiv" type="image/png">
<div style="width:200px;height:150px;>
<img src="${ImageView}" alt="" />
</div>
</script>
Js file is as follows:
var demo = new Object();
$.each(msg.images, function (key, value)
{
if (this.IsImage)
{
demo["ImageView"]="data:image/png;base64,"+this.Image;
$('#ImageDiv').tmpl(demo).appendTo("#Demo-Image");
}
});
JSON
Response is as follows:
msg = {"Images":[ "Description": "Image1", "Image": "encoded string of image", "IsImage": true, "MimeType": "image/png", } ]
less space to copy encoded string of image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With