Save canvas with an image as PNG works only in Firefox - php

I have an canvas on my site where the user can draw and can also add an image. By clicking a Save button I want the canvas to be saved as a PNG image.
Everything works fine in Firefox, but in Chrome for example when I add an image in the canvas and then try to save it, the image on the canvas has not been saved.
My code in javascript for adding an image is:
var imageObj = new Image();
imageObj.onload = function(){
x.drawImage(this, destX, destY, destWidth, destHeight);
};
imageObj.src = 'myImage.png';
Then for saving the canvas:
var drawingString = myDrawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST",'save_image.php',true);
<!-- set the mime type so the image goes through as base64 -->
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function() {
<!-- once the image data has been sent -->
if (ajax.readyState == 4){
alert("Saved");
}
}
ajax.send(postData);
and in PHP:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data like you would with traditional post
$rawImage=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers
$removeHeaders=substr($rawImage, strpos($rawImage, ",")+1);
// decode it from base 64 and into image data only
$decode=base64_decode($removeHeaders);
// save to your server
$imageFile = 'myImage.png';
$fopen = fopen($imageFile, 'w' );
fwrite( $fopen, $decode);
fclose( $fopen );
}
The problem is that the background canvas it is saved in both cases. Only the image on top of the background is note saved in Chrome, Safari or IE. Does anyone know why this code is behaved differently in Firefox and in other browsers?

Related

Issue converting obj (3d) to png [duplicate]

How would I convert a render to a .png image?
I've been looking around for awhile but nothing has worked.
Here is a function I use and a fiddle that shows it working.
function takeScreenshot() {
// For screenshots to work with WebGL renderer, preserveDrawingBuffer should be set to true.
// open in new window like this
var w = window.open('', '');
w.document.title = "Screenshot";
//w.document.body.style.backgroundColor = "red";
var img = new Image();
img.src = renderer.domElement.toDataURL();
w.document.body.appendChild(img);
// download file like this.
//var a = document.createElement('a');
//a.href = renderer.domElement.toDataURL().replace("image/png", "image/octet-stream");
//a.download = 'canvas.png'
//a.click();
}

ajax will not send canvas data to php

This is the code in my js
(function(){
var video = document.getElementById('video'),
canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
photo = document.getElementById('photo'),
vendorUrl = window.URL || window.webkitURL;
datas = canvas.toDataURL('images/png');
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true,
audio: false
}, function(stream){
video.src = vendorUrl.createObjectURL(stream);
video.play();
}, function(error){
});
document.getElementById('capture').addEventListener('click',function(){
context.drawImage(video, 0, 0, 400, 300);
photo.setAttribute('src', canvas.toDataURL('images/png'));
datas = canvas.toDataURL('images/png');
});
var canvasData = canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'webcam.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
})();
This is the php code to receive the data
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
echo "true";
// 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 );
}
?>
<head>
<meta charset="UTF-8">
<Title>Document</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="booth">
<video id = "video" width="400" height="300"></video>
Snap Shot
<canvas id="canvas" width="400" height="300"></canvas>
<img id ="photo" name = "photo" src="images/events/default.png" alt="Photo of you">
</div>
<script src="js/photo.js"></script>
</body>
<?php
?>
The application intends to take a snapshot of the user and saves the photo via javascript. I am trying to find a way to send the data back to php and utilize it to save into the database. I understand it is saved in base64 encode. I tried different methods of Ajax including the one I have saved, but the data tends to not send any data to the php folder.
Thank you in advanced.
I just suggest you to check some of you code points:
Form content type. To upload files you must use "multipart/form-data"
ajax.setRequestHeader('Content-Type', 'multipart/form-data');
You can use FormData class in JS to make form data before sending:
https://developer.mozilla.org/en/docs/Web/API/FormData/append
Canvas function "toDataURL" have no mime types "images/png". Just "image/png"

Pretty Photo load image via ajax frame

I have an angular app that will display some images. I am opening a prettyPhoto ajax window and passing the pathname to the URL. My script is loading the image fine, however, it isn't displaying the image how prettyPhoto traditionally displays a photo.
What do I need to do so it behaves like it is displaying a photo? i.e: has the fullscreen button, resizes the lightbox to the photo etc.
Is that even possible?
I am opening the lightbox via:
$scope.openLightbox = function()
{
if (typeof $.prettyPhoto.open !== "function")
{
$.fn.prettyPhoto({
social_tools:false,
deeplinking: false,
keyboard_shortcuts: false
});
$.prettyPhoto.open('resources/php/view/lightbox.php?ajax=true&path=' + $base64.encode($scope.currentFile));
return;
}
$.prettyPhoto.open('resources/php/view/lightbox.php?ajax=true&path=' + $base64.encode($scope.currentFile));
}
$scope.currentFile would be something like: data/39/my_image_name.jpg
and I am parsing the PHP like so:
$path = base64_decode($_GET['path']);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
$mimeExt = explode('/', $mime);
if ($mimeExt[0] == 'image')
{
echo '<img width="100%" height="100%" src="data:image/' . $mimeExt[1] . ';base64,' . base64_encode(file_get_contents($path)) . '">';
}
elseif ($mimeExt[0] == 'video')
{
}
finfo_close($finfo);
Like I said above, the image is displaying just fine, I just want it to be displayed with the standard prettyPhoto image behavior. I understand this may not be possible.
EDIT
So turns out I didn't need AJAX afterall:
$scope.openLightbox = function()
{
if (typeof $.prettyPhoto.open !== "function")
{
$.fn.prettyPhoto({
social_tools:false,
deeplinking: false,
keyboard_shortcuts: false
});
$.prettyPhoto.open('resources/php/view/lightbox.php?path=' + $base64.encode($scope.currentFile));
return;
}
$.prettyPhoto.open('resources/php/view/lightbox.php?path=' + $base64.encode($scope.currentFile));
}
and finally my php which I am outputting the image directly to the browser so prettyPhoto thinks it is just loading an image
<?php
require("../config.php");
require("../connect.php");
session_start();
if (isset($_SESSION['ds_level']))
{
$path = base64_decode($_GET['path']);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
$mimeExt = explode('/', $mime);
if ($mimeExt[0] == 'image')
{
header('Content-Type: image/' . $mimeExt[1]);
echo file_get_contents($path);
}
elseif ($mimeExt[0] == 'video')
{
//do other stuff to display video
}
finfo_close($finfo);
}
else
{
//-- no access
}
?>
What do I need to do so it behaves like it is displaying a photo? i.e: has the fullscreen button, resizes the lightbox to the photo etc.
Is that even possible?
Yes, it is possible. You need to create a dedicated directive, as specified in this Gist:
.directive('prettyp', function(){
return function(scope, element, attrs) {
$("[rel^='prettyPhoto']").prettyPhoto({deeplinking: false, social_tools: false});
}
})
To apply it, specify rel="prettyPhoto" in the anchor, like so:
<a prettyp ng-href="{{image.url}}" rel="prettyPhoto[main]" target="_blank" title="{{image.title}}">
HOW IT WORKS
The directive looks for a rel attribute starting with prettyPhoto, and applies the prettyPhoto magic to it.
EXAMPLE
I made a Plunk you can play around with: check the Plunk
IN YOUR CODE
To apply the directive in your code, you could replace:
echo '';
with:
echo '<img width="100%" height="100%" src="data:image/' . $mimeExt[1] . ';base64,' . base64_encode(file_get_contents($path)) . '">';
EDIT AFTER CHAT SESSION
As your images are protected with .htaccess, you have opted to work with a base64 version of your image, and why not?
However, it seems that if you wait until the user clicks the 'view' button in your app, it takes too long to go fetch the protected image and encode it, before passing it on to prettyPhoto:
I recommend you go fetch your image before the user clicks the view button, when the user selects the image in the list.
The long process of:
make an ajax call to php server;
have php app fetch image;
have php app encode image;
have angularjs/javaScript app store the base64 string
can then be done automatically, preventively, in the background.
The user experience would then be optimised.
So when the user does click the view button, the base64 version of the image can be passed to prettyPhoto straight away, without any server call: this would produce the same result as displayed in the plunkr I provided, when the button is pressed.

Passing from Javascript canvas image info AND some vars to PHP

First of all, sorry for my bad English, I'm Italian. I'm a bit new to programming, but for my office I need to create script that's a bit complex (at least for me). Before explaining the problem i'll explain what i'm doing.
I scripted a canvas that creates an image from data input, then i send the image data to php for the saving process. The problem is that i need to send also an value of 1 of the js vars (in the example value1). I can't figure out how to pass this information together with the raw image data.
The js code for the img drawing and saving. i need to pass the value1 to the save.php
button.addEventListener("click",function(){
//saving the values of the form
var value1 = document.getElementById("value1").value;
//text on the canvas
var value1X = (maxWidth-ctx.measureText(value1).width)/2+500;
//drawing the inputed text on the canvas
ctx.drawImage(img,0,0);
ctx.fillText(value1,value1X,maxHeight);
//getting the image url and sending it to save.php for the saving process
var imageURL = c.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
}, false);
Here is the PHP file:
<?php
if (isset($GLOBALS[HTTP_RAW_POST_DATA])) {
$imageData = $GLOBALS[HTTP_RAW_POST_DATA];
$imageData = str_replace('data:image/png;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$data = base64_decode($imageData);
//here i need the value1 value from the javascript
$dirname = "value1";
$filename = "header_top.png";
$newdir = mkdir($dirname);
$path = ("the/path/to".$dirname."/");
$fp = fopen($path.$filename, 'wb');
fwrite($fp, $data);
fclose($fp);
}
I hope I was able to explain myself so you can help me.
Thank you very much.
EDIT:
I think i get it, i mean for the moment it works but i don't know if it the right way doing it.
The fact is that i'm calling a php file so i simple added at the end of the url "?dir="+value1 and it works.
ajax.open("POST", 'saving.php?dir='+value1, false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
and in the php file i simply call $_GET['dir'] to get the value.
#hendrik thank you very much for your answer, unfortunaly i can't get it work with json, maybe becouse i didn't know it.
Anyway if someone knows a better way would be nice.
I think using JSON would be a good way to send the data to your PHP file. That way you can store multiple variables in an Object or Array.
// Store your data in an Object
var imageData = {
url: 'http://adsadsf.com',
name: 'foobar.gif',
width: 500,
height: 400,
directory: 'img/'
}
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
// Send the imageData object as JSON
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify(imageData));
Unfortunately I don't know enough about PHP to explain exactly how to handle the received JSON data, but I guess you can use the json_decode method for that.
More about JSON: http://www.json.org/js.html

Script to draw image

I am looking for a PHP script that will allow me to draw an image with my mouse and save it as an image. If you know of any please help.
In case you do feel like reinventing a few wheels :-)
Make a Javascript snippet that lets you draw. This can of course be as advanced or simple as you wish, for example:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
pos = false;
ctx.strokeStyle = "red";
$(canvas).bind("mousedown", function(evt) {
pos = {x: evt.layerX, y: evt.layerY};
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
});
$(canvas).bind("mousemove", function(evt) {
if(!pos) return; // You may not want to do this on every mousemove.
pos = {x: evt.layerX, y: evt.layerY};
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
});
$(canvas).bind("mouseup", function(evt) {
if(!pos) return;
ctx.closePath();
pos = false;
});
Also add a button that sends the image data to your PHP script:
$('#btn').bind("click", function(evt) {
$.post('saveImage.php', {image : canvas.toDataURL('image/jpeg')});
});
In your saveImage.php script on the server, decode the data and write it to a file.
$imgData = $_POST["image"]; // Probably a good idea to sanitize the input!
$imgData = str_replace(" ", "+", $imgData);
$imgData = substr($imgData, strpos($imgData, ","));
$file = fopen('myImage.jpg', 'wb');
fwrite($file, base64_decode($imgData));
fclose($file);
Should do the trick :-) I'm using jQuery for the JS bits here, that's of course not necessary.
PHP is executed server-side, whereas interaction with the mouse is carried out client-side. You would need to use an in-browser technology like JavaScript or Flash to capture the mouse movements and generate bitmap data first.

Categories