0

I have images stored in BLOB format in my database. My PHP code can access this BLOB data and return it to client side HTML page in JSON format.

How do I display this data on my HTML page?

I have tried using base64_encode but it works only for Firefox. THIS CODE IS NOT WORKING FOR CHROME, IE, OPERA.

Here is my PHP code:

$json2[] = array("Picture"=>base64_encode($row2[33]));
header("Content-Type: application/json; charset=UTF-8");
header("Content-type:image/jpeg");
echo json_encode($json2);

And this is my JQuery code:

success: function(data){

        var str = JSON.stringify(data);
        var obj = JSON.parse(str);
        $('#pic0').html('<img  height="40" width="40" src="data:image/jpeg;base64,' + obj[0].Picture + '" />');
}

success function is a part of AJAX call. My primary aim is to display this image in Mobile devices since this is a part of WebService Call. From what i have read, it seems base64_encode has some limitations in working for every browser.

How can I display the images on HTML page?

I have checked other posts in SO but unable to find anything fruitful.

Kaushal Shah
  • 129
  • 1
  • 2
  • 9

3 Answers3

0

These two lines of code:

$json = array(/* anything */);
echo $json;

output the following to your page, verbatim:

Array

You need to echo like this:

header("Content-Type: application/javascript");
echo json_encode($json);

Of course your Javascript frontend must properly parse this JSON string to object you use in Javascript snippet you provided.

hijarian
  • 2,159
  • 1
  • 28
  • 34
0

Answering my own question here: As suggested by @NullPoiиteя, the encoded Blob data can be displayed using this code:

$('where you want to display').html('<img src="data:image/png;base64,' + ImageVariable + '" />');
Kaushal Shah
  • 129
  • 1
  • 2
  • 9
0

there's no base64_decode in javascript/jQuery?

That's not your problem. It's relatively trivial to write a base64_decode() implementation, however in order to display the data in the browser, you would still need canvas support - and if your browser does not support data URIs then it's unlikely to support canvas.

If it were me, I would use data URIs by default, but add detection in javascript to check for an absence of support, then update the src where data URI support is not available....

function check_img()
{
   var chkimg=document.getElementById("testDataUri");
   if (checkimg.height) {
       return true;
   }
   imgs=document.getElementsByTagName("img");
   for (var i=0; i<imgs.length; i++) {
     if (imgs[i].data && imgs[i].src.match(/data:/i) {
        imgs[i].src=imgs[i].data;
     }
   }
}

(code not tested - just for illustration purposes)

symcbean
  • 47,736
  • 6
  • 59
  • 94