canvas..toDataURL and upload it - javascript

Am working on converting canvas to image and upload it to server when the user submit the form.
The image posted correctly but it appears empty in the server.
Here is my code, (Am using phonegap)
.drawImage ()is in the main.js .. but canvas..toDataURLis in a script in the html
<script>
function insert()
{
var img = document.getElementById("myCanvas")[0].toDataURL("image/jpeg");
$.ajax({
type: "POST",
url: "http://*******************/create.php?title="+ ($("#myTitle").val())+"&description="
+$("#myDesc").val()+"&price="+$("#myPrice").val(),
data: {img: img},
success: function(data)
{
alert("inserted");
}});
</script>
php
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Any idea ?
EDIT !!!
Finally it is UPLOADING!!!
Thanks to Jack Franzen for his suggestion.
I've changed the php code to
$img = $_POST['img'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.jpg';
$success = file_put_contents($file, $data);
and it is working as charm! :)

I Know your problem! Your PHP code is looking for a "PNG", but your javascript is generating a "JPG"
Just switch toDataURL("image/jpeg") To toDataURL()

Related

Php code instead of data in Ajax

I have this ajax code, pretty simple :
$.ajax({
type: "POST",
url: "save.php",
data: {
imgBase64: dataURL,
counter : time
}
});
And in the other side, I have my php file :
<?php
define('UPLOAD_DIR', 'upload/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$counter = $_POST['counter'];
$formatedcounter = sprintf('%03d', $counter);
$data = base64_decode($img);
$filename = UPLOAD_DIR . 'GWD' . $formatedcounter . '.png';
$success = file_put_contents($filename, $data);
print $success ? $file : 'Unable to save the file.';
?>
I would like to combine both. Is it possible to write the php code instead of "save.php" for data in ajax? I've already tried but I get errors in phpstorm.
Thanks a lot!
Regards.
Thanks a lot guys.
So it can only point to a file. It's not (for example) possible to write the php code after and to point to it.

I have a canvas that I am trying to send the dataURL with javascript to php using ajax post

I have a page with a canvas. I'm using signaturPad to capture a signature. I now need to send this signature to the php page to process and save
var saveButton = document.getElementById('save');
var cancelButton = document.getElementById('clear');
saveButton.addEventListener('click', function (event) {
var canvas = document.getElementById('signature-pad');
var dataURL = canvas.toDataURL();
console.log(dataURL);
$.ajax({
type: "POST",
url: "user_group_start_paperwork_esign2.php?group_id=1389",
data: dataURL,
//dataType: "html",
cache: false,
success: function(data){//console.log(data)
}
});
And on the PHP side
define('UPLOAD_DIR', 'images/');
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
But I don't seem to be sending anything. The console.log is getting the data but the $_POST['data'] seems to be empty. Thanks

How to merge base64 png and preset png in PHP

Good day. I'm currently sending data from a form to a php script to save an image. It's sent via XMLHttprequest. The base image is retrieved via $_POST['img'] and is in base 64 format. The following PHP script saves it to the server and it works perfectly fine:
<?php
session_start();
$email = $_SESSION['email'];
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = "./gallery/" . bin2hex(openssl_random_pseudo_bytes(16)) . ".png";
file_put_contents($fileName, $fileData);
$conn = new PDO("mysql:host=localhost; dbname=camagru", "root", "admin");
$conn->setAttribute(PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO `images` (`image`, `email`) VALUES (:image, :email)");
$sql->bindParam(':image', $fileName);
$sql->bindParam(':email', $email);
$sql->execute();
?>
The frame for the picture (Overlay) is sent to $_POST['frame'], but it's not a base64 image, it's a filename as follows: './frames/frame1.png'. How do I merge these two, and save it as $fileName?

How to decode base64 attachment file - Gmail API

I am using the Gmail API function in javascript:
var request = gapi.client.gmail.users.messages.attachments.get({
'userId': 'me',
'messageId': 'MyMessageId',
'id': 'MyAttachmentId'
});
request.execute(function(resp) {
var dd = new FormData();
//here resp.result.data is the base64 data of the attachment file
dd.append( "img_data", JSON.stringify( resp.result.data ) );
fetch("http://my-url",{
method: 'post',
body: dd
});
}
I am sending this data to a url, where the server code is done using php.
I am using the following code to decode the base64 data and to save the file(Just for png image files):
define('UPLOAD_DIR', './');
$img = json_decode($_POST['img_data']);
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Everything works fine, but the saved image file is corrupted and shows the error: Fatal error reading PNG image file: Decompression error in IDAT
Finally got the solution. Added the following php code:
$img = str_replace(' ', '+', $img);
$img = str_replace('_', '/', $img);
$img = str_replace('-', '+', $img);
The new code to decode and to save the file:
define('UPLOAD_DIR', './');
$img = json_decode($_POST['img_data']);
$img = str_replace(' ', '+', $img);
$img = str_replace('_', '/', $img);
$img = str_replace('-', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

How Can Inline IMG SRC data:image Be Transferred With JavaScript to PHP?

Below is an element that contains inline base64 image data (abbreviated to fit here). How can JavaScript get the inline data and send it to PHP? It would be good if an intermediate canvas can be avoided, since the raw data is already available.
In the page:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEU4Xoy9WY9k6" id="photo">
The JavaScript I'm currently using to click on the element to trigger the transfer to PHP, which saves a 0 byte .png file to disk:
$("#photo").click(function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploadPhoto.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + this.src;
xhr.send(data);
});
uploadPhoto.php, which receives the data and writes it to disk:
<?php
if ($_POST) {
define('UPLOAD_DIR', '/photos/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
} else {
print 'Unable to save ' . $_POST['image'];
}
?>
What's missing?
SOLUTION UPDATE
Per #EhsanT, the png format of the raw data was not matched in the php, so this line in the php now has png where jpeg used to be:
str_replace('data:image/png;base64,', '', $img);
The only thing you are doing wrong in this particular sample code you have provided is that you have a PNG base64 image data, and in your uploadPhoto.php file you are expecting a JPG file.
So in the uploadPhoto.php file just change this line:
$img = str_replace('data:image/jpeg;base64,', '', $img);
to this:
$img = str_replace('data:image/png;base64,', '', $img);
and you are good to go

Categories

Resources