I'm trying to send a jpg image from my page using AJAX with jquery to my server which is handling the image with a php script. I send the image like this:
function post_snapshot() {
var pic = document.getElementById('snapshot').src;
if(pic){
var jpic = JSON.stringify(pic);
$.ajax({
url:"picture",
data: jpic,
type: "PUT",
dataType: "json",
success: function(json){
console.log(json);
},
error: function(xhr, status, errorThrown){
console.log("Error: " + errorThrown);
console.log("Status " + status);
console.dir(xhr);
}
});
}
}
Then I retrieve the image with my php script:
private function create_picture($name){
$putdata = fopen("php://input", "r"); // read pic into string
$picstr = "";
while ($data = fread($putdata, 1024))
$picstr = $picstr . $data;
fclose($putdata);
$picstr = base64_decode($picstr); // decode picture
if(!picstr){
echo json_encode(array("status" => "failed to decode image"));
return;
}
$source = imagecreatefromstring($picstr);
if(!$source){
echo json_encode(array("status" => "failed to create image"));
return;
} else {
if(!imagejpeg($source,"images/img" . date_timestamp_get(date_create()) . ".jpeg")){
echo json_encode(array("status" => "failed to save image"));
return;
} else {
echo json_encode(array("status" => "success"));
}
}
Currently I get the "failed to create image" message back which means that imagecreatefromstring() is failing.
My suspicion for why it is not working is because I use JSON.stringify in my javascript which might not play nicely with php's decode function. It also might be in how I am using jquery's AJAX call.
I printed out the decoded string in php just to see what it looked like: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgDh[...]
Does anyone see anything glaringly wrong?
You should use json_decode();
// read pic into string
$putdata = json_decode(fopen("php://input", "r"), true);
I wasn't able to figure out why my original method was not working, however I got it to work by a different method.
I'm using a little library called Webcam.js which I discovered on reading the documentation that there's a built in upload function. I use the upload function and get the posted file on the php side and everything works great!
move_uploaded_file($_FILES['webcam']['tmp_name'], "images/img".date_timestamp_get(date_create()) . ".jpg");