I draw something with html5-canvas. then i want to save it, and when the page is loaded again, I want to load the image I saved back to the canvas. I succeed with saving the data into a file in the server, but for some reason it's a strange file that can't open by ant software, and ofcourse not by my canvas. I save it as png base64, but i tried other things that didn't work.
javascript code:
function save(){ //saves the canvas into a string as a base64 png image. jsvalue is sent to the server by an html form
var b_canvas = document.getElementById("a");
var b_context = b_canvas.getContext("2d");
var img = b_canvas.toDataURL("image/png");
document.classic_form.jsvalue.value = img;
}
// opens the image file and displays it on the canvas
var canvas = document.getElementById("a");
var context = canvas.getContext("2d");
var img = new Image();
img.src = "backpicture.png";
img.onload = function() {
context.drawImage(img, 0, 0);
};
php code:
<?php
$str=$_POST['jsvalue'];
$file=fopen("backpicture.txt","w");
if(isset($_POST['submit']))
fwrite($file,$str);
fclose($file)
?>
it creates the file, but shows nothing on the canvas when I load the page again.
I also tried to use Canvas2Image.saveAsPNG(), but it still didn't work.
can you please help?
thanks!
In order to save the file properly you need to decode the base64 data (and save as png):
file_put_contents('backpicture.png', base64_decode($str));
This:
.toDataURL("image/png");
Will give you something like this:
image/png;base64,iVBORw0K...[base64encoded_string]...
As #Variant said, you need to base64_decode it, but, ignoring "image/png;base64,"
This should work:
file_put_contents('backpicture.png',base64_decode(substr($str,22)));
Related
In javascript, I read the file data by binding the on-change method to the file input and saving the file data into another input using the following code
$("#release_cover_custom").on('change', function (evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
$("#release_cover_custom_data").val(e.target.result);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
});
why i use the above code?, to store the image data, because i have a form where i provide settings for the email template that would be sent later and there i have to provide the background image to be used inside the email, i need to preview the email with all the settings and along with the background image provided to upload before saving the form or uploading the image, so i read the image data, save it to an input and then open a modal window to preview email and post all the necessary variables there including the image data which is then used in the following way inside the css to apply the background-image like below in my php view file
background-image:url('" . $background_image . "') !important;
Now i want to do the achieve the same thing via php, means if i have the image saved to a path and i want to read the image data and use it in the same way i did using javascript to futher pass it to the css property,
i tried to use base64_encode(file_get_contents('path/to/file'))
but the encoding seems to be different for the image data, as the background image is not shown should i be using some other method to achieve it in php.
#quagaar reply (on the question) helped me solve the problem and replaced the following
$background_image=base64_encode(file_get_contents('/path/to/file'));
with
$background_image='data:image/png;base64,'.base64_encode(file_get_contents('/path/to/file'));
and everything works fine as expected.
EDIT:
between i was dealing with images only and if you are working with Images only and you need mime type (e.g. for headers, or like my case), then this is a fast and reliable technique:
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));
It will output true image mime type even if you rename your image file.
I have a image that is merged using php (this is in localhost). I want to automatically upload this file to a server php file that will accept it or upload it to a server folder.
The normal way is to use a form with multipart then submit form to upload it. I need to pass the image itself to the php or submit form automatically without having to do it manually.
I tried to create a directory pictures set permission to 777 and try to save the image to server
$outfile = "http://XXXXXX.com/pictures/testing.png";
$quality = 100;
imagejpeg($output,$outfile,$quality);
didn't work
Update:
Tried the canvas todataurl in localhost, it works fine but getting error when trying it on server giving
XMLHttpRequest cannot load http://xxx.com/upload_img. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
So I tried to check out how to allow access origin this but don't understand how to do it. Can someone point me to a good simple tutorial on how to do this, thanks.
I believe you have to use a Path eg( 'C:\path\filename' ) and NOT a url ( http://example.com ) for the imagejpeg function
I suggest you to use javascript to submit the form automatically and put that image upload input type within the form tag you are submitting automatically. javascript code will be some thing like this <script language="JavaScript">document.formname.submit();</script>
So found the solution using jquery $.post with Access-Control-Allow-Origin
Javascript
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.src = 'sample.jpg';
imageObj.onload = function() {
canvas.width = imageObj.width;
canvas.height = imageObj.height;
context.drawImage(imageObj, 0, 0);
var strDataURI = canvas.toDataURL();
strDataURI = strDataURI.substr(22, strDataURI.length);
$.post("http://xxxx.com/upload_img",
{
str: strDataURI
},
function(data){
//to check if any error occurs
alert(data);
});
Php file that will accept the image got the php allow-control-allow-access solution here
// * can be set to something else such as http://example.com/
header('Access-Control-Allow-Origin: *');
$data = base64_decode($_POST["str"]);
$urlUploadImages = "./uploads/";
$nameImage = "test.jpg";
$img = imagecreatefromstring($data);
imagejpeg($img, $urlUploadImages.$nameImage, 100);
imagedestroy($img);
var img = new Image();
img.src = '/images/backdrop.jpg';
ctx.drawImage(img,0,0);
I wanted to load an image from local disk on to canvas using dialog box mechanism rather than the path directly specified as in above example. I tried different sorts using JavaScript but in vain, even tried using the input type as file. What else can I try?
Take a look here:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
It's important to have drawImage call after the image has loaded:
var img = new Image();
img.onload = function() {
var ctx = document.getElementById('ctx').getContext('2d');
ctx.drawImage(img, 0, 0);
}
img.src = 'images/backdrop.jpg';
Also, note that you probably want to use images/backdrop.jpg instead of /images/backdrop.jpg (note there's no slash in front), as using the latter would get the image from root directory, I would assume that's probably not where your images are.
As far as loading from a dialog box, you can replace the last line from the above with something like this:
var name = prompt("Enter the name of the file", "backdrop.jpg");
img.src = 'images/' + name;
This way, the user would be able to enter the name of the image file to load it. Of course, you need to have that file in your images folder.
Hope this helps.
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/
I found this code to get the image size on javascript:
function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
var height = newImg.height;
var width = newImg.width;
alert ('The image size is '+width+'*'+height);
}
It works perfectly, but I need to get the size of a image that is protected; in order to access the image, I use the page image.php?id=IMAGE_ID, and it works, because in this page I check the permissions and send the image back. But when I put this link on the javascript function, in order to get its size, it doesn't work. Any help (if I put the direct link of the image it does'n work neither, because it is blocked in the .htaccess file)?
The folder that contains the images also contains a .htaccess file that denny access for everthing. To get the image, I use this PHP page:
Image.php:
//check if the user has permission
//if not, show a image with the text 'no permission'
//if it's ok
$filename = "images\\fotos\\" . $imgl;
$image = imagecreatefromjpeg($filename);
header('Content-type: image/jpeg');
imagejpeg($image, null, 100);
imagedestroy($image);
The correct way to do this is:
var newImg = new Image();
newImg.onload = function ()
{
var height = newImg.height;
var width = newImg.width;
alert ('The image size is '+width+'*'+height);
};
newImg.src = imgSrc;
If it is blocked by .htaccess, you cannot do anything about it. That means it won't be accessible from outside the server under any circumstance.
You can solve the problem that you write special php file that gets the image size and then you call this file by AJAX. However, this requires aditional server resources.