Make use of json_encode for PHP image

1

How about, I want to use json_encode to make a json of an image obtained from the database, this I have but it does not work just send me the blank page and it does not show anything of json :

<?php
 define('HOST','host.com');
 define('USER','usuario');
 define('PASS','contraseña');
 define('DB','baseDatos');

 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

  $sql = "select imagenes from imagenes";

 $res = mysqli_query($con,$sql);
 /*$resultado= mysqli_fetch_array($res);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $resultado['imagenes'] ).'"/>';*/


 $result = array();

 while($row = mysqli_fetch_array($res)){
 array_push($result,array('url'=>$row['imagenes']));
 }


 echo json_encode(array("result"=>$result));

 mysqli_close($con);


?> 

It should be noted that I have 2 images in the database and they are of type BLOB

    
asked by x4mp73r 09.05.2016 в 21:01
source

2 answers

2

This could help you

PHP

ob_start();
imagepng($my_img);
$imageData = ob_get_contents();
ob_clean(); 

$results = array(
  'price' => $_GET['priceX'],
  'image' => base64_encode($imageData)
);

$json = json_encode($results);
echo $json;

Javascript

$.getJSON("/ajax-script.php", function(data) {
  $("#element").append($("<img />").attr('src', 'data:image/png;charset=utf8;base64,' + data.image));
});
    
answered by 09.05.2016 в 21:12
1

URLs can have special characters, so, if that specific image URL has them, when entering it into the array, the code will detect the non-escaped special characters and you will have an error. Therefore, what you might try is something like this:

$result = array();

$src =  mysqli_real_escape_string($con, $row['imagenes']);

while($row = mysqli_fetch_array($res)){
    array_push($result, array('url'=> $src));
}

Test if that works for you. The URL should be saved with the special characters "escaped", and that way you should be able to get the URL within your array without any problem.

    
answered by 10.05.2016 в 03:11