I want to save a html canvas element as an image using php and jquery ajax. Here is my code for ajax.
var front_image=canvas.toDataURL("image/png");
//front image is a base_64 string
$.ajax({
url:base_url+'tabs/profile/save_front_image',
type:'POST',
data:'front_image='+front_image,
success:function(response){
}
});
I m just doing echo
in php echo $_POST['front_image']
so request and response are same.
When i use this code before ajax it loads image to new tab of browser
var w = window.open('about:blank', 'image from canvas');
w.document.write("<img src='" + frame_image + "' alt='from canvas'/>");
but when i put the same code on ajax response as bellow it doesn't work. Only a blank tab opens in browser. So i m not being able to save image as file.
var w = window.open('about:blank', 'image from canvas');
w.document.write("<img src='" + response + "' alt='from canvas'/>");
I compared string length of frame_image
and response
also. They are same. I m not sure why image is not loading in response. Please suggest me the answer thanks.
// soon you can use front_image=canvas.toBlob("image/png")
// construct a blob
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
// make an actually file from the base64 so we can send binary data
var blob = b64toBlob(front_image.split(",")[1], "image/png")
var fd = new FormData();
fd.append("file", blob, "filename.png");
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
// The saving
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = $_FILES["file"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>