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?
Related
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 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.';
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
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()
i have this code, either the ajax isn't transferring the data correctly or my php doesn't work properly. i know the canvass is saving to data png it writes to the page. Is there a way to just convert it to a file and save it from javascript?
START JAVASCRIPT:-------------------
<-- get the canvass element and convert to data png -->
var canvas = document.getElementById("textCanvas");
var img = canvas.toDataURL("image/png");
<-- END the canvass element and convert to data png -->
<-- SEND to php file -->
var onmg = encodeURIComponent(img);
var xhr = new XMLHttpRequest();
var body = "img=" + onmg;
xhr.open('POST', "convertit.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Length", body.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(body);
xhr.onreadystatechange = function () {
if (xhr.status == 200 && xhr.readyState == 4) {
document.getElementById("div").innerHTML = xhr.responseText;
} else {
document.getElementById("div").innerHTML = 'loading';
}
}
<-- END send to php file -->
END JAVASCRIPT:-------------------
START PHP:-------------------
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/uploads/file.png', $data);
END PHP:-------------------
changed the php to -------->
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . 'txtimg.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
which i got from ----->http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html
-cheers works awesome :)