简体   繁体   中英

how to retrieve images using json in php

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.

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;
$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.

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);
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM