sending an image and return it using json?

31,123

Solution 1

The JSON MIME type is application/json, so you can't send image/jpeg.

I think it would be easier to send the path to the image, and have your JavaScript make the request to the image.

Otherwise, I'm not sure how you are going to recreate that on the client. Date URIs are recommended to be base64 encoded, so if you insist on doing it like this, please call base64_encode() first on it.

Solution 2

$media = json_decode($_POST['media']);

How exactly are you sending your image to this script? File uploads in PHP are placed into the $_FILES array, not $_POST. Unless your client-side script is doing something funky, a file send from client->php would never show up in _POST.

imagejpeg($image, '', 90);

This line will output the image as .jpg content immediately, without saving it to a file. You then do

 echo json_encode($response);

which would be a small snippet of JSON data. However, you've already output the image's binary data with the imagejpeg() call, so now you're appending some garbage to the file you send.

Besides, $image is not the binary data of the image. It's a handle into the GD system, which is a resource. Doing json_encode on it will not give you a json'd .jpg, it'll give you a json'd PHP object of some sort.

Share:
31,123
getaway
Author by

getaway

im in love with web technolgies!!

Updated on May 18, 2020

Comments

  • getaway
    getaway about 4 years

    im trying to send image to a webservice in php using json, but the client cnt read the image.. when i return it back!!

    <?php
    
    //recieve the image
    
    $media = json_decode($_POST['media']);
    
    header('content-type: image/jpeg');
    $image = imagecreatefromjpeg($media);
    imagefilter($image,IMG_FILTER_GRAYSCALE);
    imagefilter($image,IMG_FILTER_COLORIZE,100,50,0);
    imagejpeg($image, '', 90);
    imagedestroy($image);
    
    //return image
    
    $response = array(  
             'image' => $image
         );  
         echo json_encode($response);
    
    ?>
    

    from the code, is there anything I'm doing wrong? Thanks!!! :))