Send image from browser to server - possible? - php

There's an image gallery site, and the user can manipulate the images via javascript and HTML5 canvas. Is it possible to send back the manipulated image to the server for storing with PHP?

HERE you can find a complete article on the subject. But here's the short version and source codes:
First you need to convert the canvas binary data as a base 64 encoded string to send it to server:
var image = canvas.toDataURL("image/png");
Send this with an ajax call:
var ajax = new XMLHttpRequest();
ajax.open("POST",'save.php', false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(image);
Finally the PHP script save.php looks like this:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
The PHP script parses the raw post data, converts from base 64 to binary, and saves to a file. For more information on Base 64 check out THIS Wikipedia article.

Yes, canvas supports returning the image data as either Base64 encoded data url or Blob. See http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-canvas-todataurl . You can then grab the data url and post it using AJAX to your server, and Base64-decode it there.

Related

Saving base64 image to server not working in PHP

Iam getting base64 image in a json like below format
{
"profilepic":"iVBORw0KGgoAAAANSUhEUgAAAPAAAABGCAYAAADyxhn6AAAMYml..."
}
I have a PHP code like below, where i decode this base64 image and save it in server, i tried to run the code and am not able to see the image in particular folder location.
Can anyone help me to identify the problem here?
<?php
header("Access-Control-Allow-Origin: *");
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$photo = $response["profilepic"];
// Obtain the original content (usually binary data)
$bin = base64_decode($photo);
// Load GD resource from binary data
$im = imageCreateFromString($bin);
// Make sure that the GD library was able to load the image
// This is important, because you should not miss corrupted or unsupported images
if (!$im) {
die('Base64 value is not a valid image');
}
// Specify the location where you want to save the image
$img_file = 'test/'.uniqid().'.jpg';
// Save the GD resource as PNG in the best possible quality (no compression)
// This will strip any metadata or invalid contents (including, the PHP backdoor)
// To block any possible exploits, consider increasing the compression level
imagejpeg($im, $img_file, 80);
$imgPath = 'http://serverip/'.$img_file;
?>
Please help me to identify the issue

PHP base64 encode a pdf file

I am using an API where I can send a document to something like dropbox. According to the documentation, the file which is sent needs to be BASE64 encoded data.
As such, I am trying something like this
$b64Doc = chunk_split(base64_encode($this->pdfdoc));
Where $this->pdfdoc is the path to my PDF document.
At the moment, the file is being sent over but it seems invalid (displays nothing).
Am I correctly converting my PDF to BASE64 encoded data?
Thanks
base64_encode takes a string input. So all you're doing is encoding the path. You should grab the contents of the file
$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));
base64_encode() will encode whatever string you pass to it. If the value you pass is the file name, all you are going to get is an encoded filename, not the contents of the file.
You'll probably want to do file_get_contents($this->pdfdoc) or something first.
Convert base64 to pdf and save to server path.
// Real date format (xxx-xx-xx)
$toDay = date("Y-m-d");
// we give the file a random name
$name = "archive_".$toDay."_XXXXX_.pdf";
// a route is created, (it must already be created in its repository(pdf)).
$rute = "pdf/".$name;
// decode base64
$pdf_b64 = base64_decode($base_64);
// you record the file in existing folder
if(file_put_contents($rute, $pdf_b64)){
//just to force download by the browser
header("Content-type: application/pdf");
//print base64 decoded
echo $pdf_b64;
}

Saving blob video with php

I am trying to send a buffered video to save it as a file on my server.
Always the file is empty.
My js get the url "blob:https://..." and sends to the php that receive it.
$file = file_get_contents(url);
file_put_contents($video_url_mp4."helloWorld.webm",$file);
I tried send the video as canvas and i only get one frame.
suggest please
A blob url is only usable in the browser that created it. So you cant use it on your server or copy and paste it into another browser or send the link to your friend etc.
What you need to do is get the blob that url was created from and use a FormData object and upload that to your server.
I get a file with the content as string on my php but this is not in a video format.
my js:
var myFile = new File(video.src);
var fd = new FormData();
fd.append('data', myFile);
and my php:
$f = $_POST['data'];
$decode = base64_decode(preg_replace('/^data\:image\/webp\;base64\,/', '', $f));
what is wrong?

converting contents of a div into an image

I am creating an image editor type web application. I have a main div which will contain many div inside it.
When the user clicks on a save button, I want to save the main div as an image in a folder.
I tried doing it using Canvas.toDataURL() but then I found that i cant place a div(main div) inside canvas tags. I also tried imagegrabscreen() function of php but it captured the screen before the whole page is loaded, so it was of no use.
Can anybody help me and suggest a way to implement this using php or javascript?
Why are you using a bunch of divs when you could just use one canvas and draw on it with proper canvas functions?
There are plenty of examples of what you're trying to do, such as this one.
use this code to save image from canvas
function save_canvas_img()
{
var canvas = document.getElementById("your id");
var canvasData = canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'save.php',false);
ajax.setRequestHeader('Content-Type', 'application/your page name');
ajax.send(canvasData );
alert('You have successfully saved this image');
}`enter code here`
here save.php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
// Need to decode before saving since the data we received is already base64 encoded
//echo "unencodedData".$unencodedData;
$randomName = mktime(). rand(99999,9999999). '.png';
$fp = fopen( 'foldername/'.$randomName, 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );}`enter code here`
If you want to take a 'screenshot' of your main div check out the links below
Using HTML5/Canvas/JavaScript to take screenshots
http://html2canvas.hertzen.com/

uploading canvas context as image using ajax and php

I have a canvas and I want to upload the canvas context to the server using ajax and php. I want the final output to be an image stored on the server. I have done image uploading using form. But now I want to get the canvas context convert it to image and upload to the server!
So, how can i do that? Any suggestions, algos or solutions are appreciated!
This blog post aptly describes the method of saving canvases onto the server with AJAX queries, I guess this should be fitting for you.
Basically, you will need a var canvasData = testCanvas.toDataURL("image/png"); to retrieve the canvas' contents in JavaScript. This will be a Base64 encoded string, something like this: data:image/png;base64,fooooooooooobaaaaaaaaaaar==.
The following code will make sure the AJAX query sends the contents to the HTML:
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
On the server, in the PHP script, you will have a key named HTTP_RAW_POST_DATA in the $GLOBALS array, this will contain the data we just fetched.
// Remove the headers (data:,) part.
$filteredData=substr($GLOBALS['HTTP_RAW_POST_DATA'], strpos($GLOBALS['HTTP_RAW_POST_DATA'], ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$decodedData=base64_decode($filteredData);
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $decodedData);
fclose( $fp );
Of course, test.png is the filename you will save. The first line is required to remove the data:image/png;base64, part of the encoded image, so that it can later be decoded by base64_decode(). It's output ($decodedData) will be saved to the file.

Categories