Send image and return it using json?

im trying to send the image to webservice in php using json, but the cnt client is reading the image. when i get 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 something I am doing wrong? Thank you !!! :))

+4
source share
4 answers

The JMON type is MIME application/json , so you cannot send image/jpeg .

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

Otherwise, I'm not sure how you are going to recreate this on the client. For date URIs, it is recommended to use base64 encoding, so if you insist on it, please call base64_encode() .

+7
source
 $media = json_decode($_POST['media']); 

How exactly do you submit your image to this script? Uploading files in PHP is placed in the $ _FILES array, not $ _POST. If your client side of the script does something funky, sending the file with client-> php will never appear in _POST.

 imagejpeg($image, '', 90); 

This line displays the image as .jpg content immediately, without saving it to a file. Then you do

  echo json_encode($response); 

which will be a small piece of JSON data. However, you have already outputted the binary image data using the imagejpeg() call, so now you are adding garbage to the file to be sent.

In addition, $image not binary image data. This is the handle to the GD system, which is a resource. Running json_encode on it will not give you json'd.jpg, it will give you some kind of json'd PHP object.

+2
source

Maybe use imagedestroy () after creating and sending json response instead

0
source

I used this approach to get images from my server: Receive images from a PHP server on Android

0
source

Source: https://habr.com/ru/post/1341640/


All Articles