dimanche 19 avril 2015

Generate an image via PHP

I want to generate an image via php. I've already done it with a POST request that sends a base64 code representing the content of a canvas to a php file.


JS:



var canvas = document.getElementById("myCanvas");
var dataURL = canvas.toDataURL("image/jpeg", 0.2);
console.log(dataURL);

// post the dataUrl to php
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
// you will get back the temp file name
// or "Unable to save this image."
console.log(respond);
});


PHP:



<?php
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
$dataURL = $_POST["image"];
$parts = explode(',', $dataURL);
$data = $parts[1];
$data = base64_decode($data);
// create a temporary unique file name
$file = "img/" . UPLOAD_DIR . uniqid() . '.png';
// write the file to the upload directory
$success = file_put_contents($file, $data);
// return the temp file name (success)
// or return an error message
print $success ? $file : 'Unable to save this image.';
}
?>


I've looked to some similar sites and I've found out that they're doing the same thing with a different approach. They send a GET request to a php file, and they just send some datas (for example, the User name that has to be printed on the canvas).


My point is: speaking only about the server's performance, what is the best choice? If the best is second one, how can I achieve that result whit GET? Where I've to put the canvas? Thank you all!


Aucun commentaire:

Enregistrer un commentaire