如何在php中使用json检索图像

时间:2014-10-13 03:15:42

标签: javascript php json

我想从php中的json中检索图像。其实我想通过php获取这些图像源作为json数据并使用javascript显示。但我认为我做错了请帮助。

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

请帮忙。我无法找到如何使用json获取图像的解决方案。

3 个答案:

答案 0 :(得分:1)

您可以使用php将图像转换为Base 64字符串,并使用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));

然后你可以简单地将该字符串放入带有javascript的图像元素的SRC属性中。

var obj = JSON.parse(serverResponse);
img.src=obj.image;

答案 1 :(得分:1)

{{1}}

我使用上面的代码来显示图像。它以加密格式出现。 之后,您可以通过JS中的src简单地显示图像。

答案 2 :(得分:0)

我使用此代码返回保存在MySQL数据库中的文本和图像。我使用PHP访问,返回的数据在Android应用程序上运行。

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