Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 992
rebelliard Avatar asked Feb 25 '11 15:02

rebelliard


4 Answers

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.

like image 98
Fredrik Leijon Avatar answered Nov 19 '22 17:11

Fredrik Leijon


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.

like image 25
Tesserex Avatar answered Nov 19 '22 17:11

Tesserex


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.

like image 22
decyclone Avatar answered Nov 19 '22 19:11

decyclone


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.

like image 1
Pushp Avatar answered Nov 19 '22 19:11

Pushp