uploading canvas context as image using ajax and php - 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.

Related

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/

Send image from browser to server - possible?

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.

How to obtain image/png content via PHP

This is my first post to Stack Overflow so please forgive me if I have used incorrect formatting or conventions. I am trying to write a test scenario which receives a png image from a webpage POST (multipart/form-data), strips out the image which was posted and forwards that on to a 3rd party as Content-Type: image/png.
I have a php file (catcher.php) which is the recipient of the forwarded image. Post.php, the php file that posts the uploaded image to catcher.php is below:
<?php
$img = imagecreatefrompng($_FILES['myfile']['tmp_name']);
imagepng($img);
$opts = array(
'http'=>array(
'method'=>"POST",
'content'=>$img,
'header'=>"Content-Type: image/png\r\n"
)
);
$context = stream_context_create($opts);
file_get_contents( "http://localhost/catcher.php", false, $context);
?>
Post.php gets the file just fine from the webpage that posts it as multipart/form-data, however I am unsure how to access the image/png content in catcher.php.
My question is, in catcher.php, how do I access the image content? I have tried $_POST['content'] and I obtain the following error: "Undefined index: content". So I know I am just not looking for the correct data. Is there a specific superglobal variable such as $_POST or $_REQUEST that I can use to access the posted image content, or is there some other solution?
RESOLUTION
I was able to find the result I was looking for with the following code for catcher.php:
$input = fopen("php://input","+r");
$destination = fopen($target_path, 'w');
stream_copy_to_stream($input, $destination);
fclose($input);
fclose($destination);
?>
Thank you both Marc and Brenden for your expedient responses!
imagepng($img) does an immediate output of the binary garbage comprising the PNG. it's not captured into a variable. What you're actually posting is a string that probably says "GD Resource #7" or something similar.
The whole imagepng() bit is useless anyways - you're decoding a PNG into an in-memory representation, then trying to re-encode to PNG again. A pointless waste of memory, since the file is already on disk. You could do the whole thing with:
<?php
if ($_FILES['myfile']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['myfile']['error']);
}
$opts = array(
'http'=>array(
'method'=>"POST",
'content'=> file_get_contents($_FILES['myfile']['tmp_name']),
'header'=>"Content-Type: image/png\r\n"
)
);
$context = stream_context_create($opts);
file_get_contents( "http://localhost/catcher.php", false, $context);
Note the addition of checking for upload success - assumingn an upload succeeded will cause you grief down the line.
That being said, you're also not doing a proper POST file upload. For that to work, you have to actually simulate a full-blown HTML form with <input type="file"> present, and enctype="multipart/form-data" and whatnot. All you're doing is sending a raw PNG to the server.
You can probably retrieve it by reading from php://input in your catcher script.
The problem is that your data isn't encoded as multipart/form-data, it's just a PNG.
You have two options:
Encode the data correctly for a POST -- then you can read it from $_POST or $_REQUEST.
Keep post.php how it is and read the raw data from php://input in catcher.php.
For option 1, it looks like HttpRequest handles form encoding for you.

AS3 Load PNG from PHP

I need some help with loading a PNG file from a server into my flash project. What I want to do it be able to call a PHP page and send it a variable which I can do. Then I want to access a db and get a path for the image, I can do this too. What I'm not sure about is what to do then.
What I need to happen is the PHP to return the PNG to flash somehow. Can I just add the PNG to the php page and use a loader somehow? I've been searching around google but most tutorials seem to be getting PNGs out.
Thanks
Ben
It is actually pretty easy. : )
<?php
// do some mysql magic.
// let's assume you get a filename back as $file_name;
header('Content-type: image/png');
readfile($file_name);
Note that you may have to include some path info as well. Not sure where your images are stored, but if the image are in /var/www/public/images, you'd wany to prepend that into your file_get_contents call.
Added: also, if you just want to return a path to the PNG, you can do a URLRequest to a PHP file, let it figure out where the image lives, and return a URL. This is even easier... I'd just recommend standardizing on a data interchange protocol like XML or (even better) JSON... that way, if you ever decide that you want to break out of Flash and into browser technologies, your backend will already be waiting for you.
<?php
// do some mysql magic.
// let's assume you get a filename back as $file_name;
$retVal = array('pathname'=>$file_name);
header('Content-type: application/json');
echo json_encode($retVal);
if you can just return the url to the flash it will be sufficient.
import flash.display.*;
import flash.net.URLRequest;
var rect:Shape = new Shape();
rect.graphics.beginFill(0xFFFFFF);
rect.graphics.drawRect(0, 0, 100, 100);
rect.graphics.endFill();
addChild(rect);
var ldr:Loader = new Loader();
ldr.mask = rect;
var url:String = ""; //put the returned img url you got from the php here.
var urlReq:URLRequest = new URLRequest(url);
ldr.load(urlReq); //the loader will start loading the img
addChild(ldr); //here you add the loader to stage.
maybe for a millisec or two you just see nothing. But as soon as the loader has loaded the img you will see it.
You must input the returned img url. So not the url to the webpage that returns the img url.
If you combine the above with the answer of John Green - PageSpike you can use my code as long as the php page is that of the one in John Green - PageSpike his answer and you pass instead of the returned img then pass the url to the php page with parameter;
var url:String = "http://www.yoursite.com/getImage.php?imgParameter=image123";
So the url is now the link to the script of John Green - PageSpike which will return infact the image.
As Jhon Green has mentioned, it will work
http://www.yourserver.com/filesforflash/?file_id={id}
header('Content-type: image/png');
readfile($file_name);
but some times you may need also need the above url will not work even if you send headers of content type image/png. Quick tip for that is to send file name itself instead if its id
http://www.yourserver.com/filesforflash/{id}-filename.png
For this you may need to use mod-rewrite.

Categories