rebelliard
rebelliard

Reputation: 9611

Render byte[] to image using jQuery

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:

  1. Server-side / C#: string json = JsonConvert.SerializeObject(employee);
  2. Client-side / Ajax: $('#image').attr('src', "data:image/jpg;base64,"+employee.Image);

Upvotes: 8

Views: 14892

Answers (4)

Pushp
Pushp

Reputation: 11

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.

Upvotes: 1

Tesserex
Tesserex

Reputation: 17314

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.

Upvotes: 7

decyclone
decyclone

Reputation: 30840

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.

Upvotes: 3

Fredrik Leijon
Fredrik Leijon

Reputation: 2802

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.

Upvotes: 9

Related Questions