Generate Png-file With Php From Datauri Sent Through Ajax
I have an svg file that is generating a dataURI-png and that works great. And I want that dataURI to be saved as an image, therefore I try to send the dataURI through ajax to anoth
Solution 1:
You can use canvas.toBlob()
, send image to php
as a Blob
, use php://input
to read Blob
at php
, see Beyond $_POST, $_GET and $_FILE: Working with Blob in JavaScript and PHP
javascript
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", {
value: function (callback, type, quality) {
var binStr = atob( this.toDataURL(type, quality).split(",")[1] ),
len = binStr.length,
arr = newUint8Array(len);
for (var i=0; i<len; i++ ) {
arr[i] = binStr.charCodeAt(i);
}
callback( newBlob( [arr], {type: type || "image/png"} ) );
}
});
}
can.toBlob(function(blob) {
var request = newXMLHttpRequest();
// to receive `echo`ed file from `php` as `Blob`// request.responseType = "blob";
request.open("POST", "readBlobInput.php", true);
request.setRequestHeader("x-file-name", "filename");
request.onload = function() {
// `this.response` : `Blob` `echo`ed from `php`// console.log(this.response)console.log(this.responseText);
}
request.send(blob)
});
readBlobInput.php
<?php// the Blob will be in the input stream, so we use php://input$input = file_get_contents("php://input");
// choose a filename, use request header$tmpFilename = $_SERVER["HTTP_X_FILE_NAME"];
// http://stackoverflow.com/q/541430/$folder = __DIR__ . "/tmp-png";
// http://stackoverflow.com/q/17213403/
is_dir($folder) || @mkdir($folder) || die("Can't Create folder");
// put contents of file in folder
file_put_contents($folder . "/" . $tmpFilename, $input);
// get MIME type of file$mime = mime_content_type($folder . "/" . $tmpFilename);
$type = explode("/", $mime);
// set MIME type at file$filename = $tmpFilename . "." . $type[1];
// rename file including MIME type
rename($folder . "/" . $tmpFilename, $folder . "/" . $filename);
// to echo file // header("Content-Type: " . $type); // echo file_get_contents($newName);echo$filename . " created";
?>
Solution 2:
$dataUrl = $_REQUEST['datauri'];
$id = $_REQUEST['id'];
list($meta, $content) = explode(',', $dataUrl);
$content = str_replace(".", "", $content); // some android browsers will return a data64 that may not be accurate without this without this.$content = base64_decode($content);
$image = imagecreatefromstring($content);
imagepng($image, './tmp-png/'.$id.'.png', 90); // Third parameter is optional. Just placed it incase you want to save storage space...
Post a Comment for "Generate Png-file With Php From Datauri Sent Through Ajax"