im trying to send image to a webservice in php using json, but the client cnt read the image.. when i return 开发者_如何学JAVAit 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!!! :))
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.
$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.
Perhaps use imagedestroy() after building and sending the json response instead of before
I used this approach to get an image from my server: Get images from PHP server to Android
精彩评论