How to upload images to canvas, when user uploads images [duplicate] - php

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.

Related

how to read image file as data url using php

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.

Upload a picture in php without submitting a form manually

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);

PHP - Extract frame during Video upload

I'm having a problem finding if this is even possible (no info anywhere to be found).
Is it possible to EXTRACT a frame (thumbnail) during the video upload?
Extract using jscript is also an option if it's possible to extract user side.
Thanks for the help!
Fast forward almost five years since this question was posted, and the answer is now a yes!
Live demo
How to extract a frame during video upload using JavaScript
Before showing code, this is what we'll do:
Set an event handler on the input element that will take the video to be uploaded
When a file is selected from the file system, use the URL object to create a url to the local video file.
Load that URL into a video element.
When the video has loaded into memory, draw a frame on a canvas object.
Now export the frame rendered on the canvas into an image element (or optionally send that image to your server as a data url).
<input type="file" id="upload"/>
<img id="thumbnail"/>
<script>
var input = document.getElementById('upload');
var img = document.getElementById('thumbnail');
input.addEventListener('change', function(event){
var file = this.files[0];
var url = URL.createObjectURL(file);
var video = document.createElement('video');
video.src = url;
var snapshot = function(){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
img.src = canvas.toDataURL('image/png');
video.removeEventListener('canplay', snapshot);
};
video.addEventListener('canplay', snapshot);
});
</script>
I don't think there is a good way to do that in php. (https://stackoverflow.com/a/1309425/1488032)
If it is not just some webspace that you have rented but have the rights to install and run other software on the server I would suggest using something like ffmpeg and calling it from within php using system(), passthru() or exec() to extract what you want and do the rest of the processing in php again.
I'm running a browser game that relies on svg images embedded in xhtml but some browsers (especially mobile ones) don't support the full svg syntax. In this case I use such a system() call to do svg-to-png conversion using imagemagick's convert binary and display the result on my page.
system("echo '$svgString' | convert svg:- png:- | base64");
I suppose you have to fall back to something similar.
Here's some information on extracting frames using ffmpeg:
http://ubuntuforums.org/showthread.php?t=1141293
Javascript: no.
During upload: no.
Once you've uploaded, yes.
"Dev" provided the right link in the comments, but what you should do is save the video to your server and then run ffMpeg to grab the image. You can download ffMPEG here: http://ffmpeg.org/download.html (grab hte build you need if you're not confident on building it yourself - there are Linux and Windows builds).
The documentation is here: http://ffmpeg.org/ffmpeg.html but there is a slightly easier to read tutorial at http://linuxers.org/tutorial/how-extract-images-video-using-ffmpeg for grabbing an image.
Note: there is a PHP extension clled "phpFFMPEG" but I suggest you don't use it. Simply run the desired commands through "exec()" in PHP. Check for error return values as you can only run ffMPEG once per CPU core, so if you try it twice at the same time it might fail - either queue the actions or try again if it fails.
First, you need to select a program to extract the frame. ffmpeg is commonly used for this. Whatever you pick, it needs to be able to work with partial file contents.
php scripts dont start executing until after the entire file upload has completed, but php recently got a feature so that a different php script can be executed during the file upload, and will be able to get at uploading scripts data(the filename is the thing of interest to you).
http://php.net/manual/en/session.upload-progress.php
Then, basically call the external program to extract the frame from the monitoring script, using the temp file name being uploaded in the upload handling script.
to summarize:
upload the file to upload.php.
monitor.php will get the temp file name being uploaded in upload.php, and extract the frame.
Basically, I took rodrigo-silveira answer provided in this thread and modified it for my use and now the solution works like a charm. Even I was trying to upload the video thumbnail/poster of a video that a user wishes to upload and save the video and the thumbnail in a folder. Also, I didn't want to use ffmpeg.
Here is what I did: In the upload file called "upload.php" I have the following code with slight modification to rodrigo-silveira's solution above:
upload.php:
<input type="file" id="upload"/>
<img id="thumbnail"/>
<form action="action_page.php" method="post" target="_blank">
<input type="hidden" id="mytext" name="mytext" >
<input type="submit" value="Submit">
</form>
<script>
var input = document.getElementById('upload');
var img = document.getElementById('thumbnail');
input.addEventListener('change', function(event){
var file = this.files[0];
var url = URL.createObjectURL(file);
var video = document.createElement('video');
video.src = url;
var snapshot = function(){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 350;
canvas.height = 250;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
img.src = canvas.toDataURL('image/png');
document.getElementById("mytext").value = img.src;
video.removeEventListener('canplay', snapshot);
};
video.addEventListener('canplay', snapshot);
});
</script>
Both the HTML part and the JavaScript above are within the upload.php's body tag.
Now on to the action_page.php file:
<?php
$data = $_POST['mytext'];
$file = "photos/file".time().".png";
$uri = substr($data,strpos($data, ",") + 1);
file_put_contents($file, base64_decode($uri));
?>
Save both PHP files in the same folder and create another folder called "photos" in that folder. Your video thumbnail/poster image from a video that is selected in the upload.php page gets saved in the "photos" folder as png file. (Note: this solution does not upload the video, just the video thumbnail. But that is straight forward from here on.)

Javascript get image size from php generated image

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.

HTML5 CANVAS: How to save and reopen image from server

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)));

Categories