1

I want to retrieve images from json in php. Actually I want to get those images sources as json data through php and display using javascript. But I think m doing something wrong please help.

<script type="text/javascript">
function jsonGetImages(name){
var thumbnailbox = document.getElementById("picturebox");
var hr = new XMLHttpRequest();
hr.open("POST", "jsonget.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var d = JSON.parse(hr.responseText);
        picturebox.innerHTML = "";
        for(var o in d){
            if(d[o].src){
                picturebox.innerHTML += '<img src="'+d[o].src+'">';
            }
        }
    }
}
hr.send("name="+name);
picturebox.innerHTML = "requesting...";
 }
 </script>
 </head>
 <body>
 <div id="picturebox"></div>
 <script type="text/javascript">jsonGetImages('Jason');</script> 
  </body>

jsonget.php

<?php
 header("Content-Type: application/json");
 $folder = 'images';
 $cn=mysql_connect("localhost","root","");
if(!$cn){
    echo "<b>Connection couldn't be established.</b>";
    die();
}
$db=mysql_select_db("test",$cn);
if(!$db){
    echo "<b>Database doesn't exist.</b>";
}
$dir = $folder."/"; 
$dirHandle = opendir($dir);
$name=$_POST['name'];
$sql="SELECT * FROM users WHERE name='$name'";
$result=mysql_query($sql);
echo mysql_num_rows($result);
$i=0;
$jsonData = '{';
while($row=mysql_fetch_array($result)){
$name=$row['name'];
$image_name=$row['image'];  
$i++;
$file=readdir($dirHandle);
    $src = "$dir$image_name";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$name.'" },';
  }
 closedir($dirHandle);
 $jsonData = chop($jsonData, ",");
 $jsonData .= '}';
 echo $jsonData;
 ?>

Please help. I can't find solution how to get images using json.

3 Answers 3

4

You can convert the image to a Base 64 string with php and pass it with JSON

$src = "$dir$image_name";
$type = pathinfo($src, PATHINFO_EXTENSION);
$data = file_get_contents($src);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$myobj = json_encode(array("image"=>$base64));

Then you can simply put that string into the SRC attribue of an image element with javascript.

var obj = JSON.parse(serverResponse);
img.src=obj.image;
Sign up to request clarification or add additional context in comments.

1 Comment

@Jason - Happy to help, I just noticed and fixed an error in the snippet I posted so please check it again it you copied my example. Also, now that your question has been answered please click on the check mark to select it :)
1
$res = mysqli_query($conn,"SELECT * FROM table_name");
        while($row  = mysqli_fetch_array($res)){

            echo '<img src="data:image/jpeg;base64,'.base64_encode($row['al_image']).'" >';

        }

I use above code for displaying image. it came in the encrypted format. after that, you can simply display image through src in JS.

Comments

0

I use this code to return text and image that are saved in the MySQL database. I use PHP to access and the data returned am running on an Android application.

<?php

/*******************************************************
{                                                       }
{                   GET IMAGE JSON                      }
{                                                       }
{          File: GetImageJson.php                       }
{          Copyright (c) Zicatti Software  2015         }
{          Developer: Osmir Zicatti                     }
{                                                       }
{                                                       }
{     Used to return the fields in a table              }
{     containing image ( BLOB ) using json              }
{                                                       }
{*******************************************************}

{*******************************************************}
{  Paramentro necessário: Numero da pagina              }
{  Formato de chamada: GetImageJson.php?PAGINA=1        }
{*******************************************************/

$Pagina = @$_GET['PAGINA'];

if (@$_GET['PAGINA'] != '') {

$host="200.200.200.200"; // Host name 
$username="BDados"; // Mysql username 
$password="password"; // Mysql password 
$db_name="DATABASE"; // Database name 

    // Connect to server and select databse.
    mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB");


    mysql_set_charset('utf8');
    // retorna TODOS os campos com as 2 imagens
    // $qry = sprintf("SELECT id, pagina, titulo, texto1, texto2, image_thumb, imagem FROM TABELA where pagina = %s",

    // Mas vou usar esta para carregar a ListView com o thunmbnail que é menor
    $qry = sprintf("SELECT id, pagina, titulo, texto1, texto2, image_thumb FROM TABELA where pagina = %s",
        mysql_real_escape_string($Pagina));
    $query=mysql_query($qry);       

    if (!$query) {
                $message  = 'Invalid query: ' . mysql_error() . "\n";
                $message .= 'Whole query: ' . $qry;
                die($message);
    }

    $return_arr = array();
    $row_array = array();

    // Verifica se existe algum registro
    $num_rows = mysql_num_rows($query);
    if ($num_rows > 0) {
        while ($r = mysql_fetch_array($query)) {
            $row_array['id'] = $r['id'];
            $row_array['pagina'] = $r['pagina'];
            $row_array['titulo'] = $r['titulo'];
            $row_array['texto1'] = $r['texto1'];
            $row_array['texto2'] = $r['texto2'];
            $row_array['image_thumb'] = base64_encode($r['image_thumb']);

            array_push($return_arr,$row_array);
        }
    }
    else { $return_arr['id'] = 'ERRO - Pagina inexistente'; }

    echo json_encode($return_arr);
    return json_encode($return_arr);

    mysql_close();
}
else { 
     $return_arr['id'] = 'ERRO - Faltou enviar o numero da pagina';
     echo json_encode($return_arr);
    return json_encode($return_arr);
    }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.