14

I'm developing a web application which browse and take pictures from local and also I want to capture images through the camera. Im using the following code and i can capture device camera.

<input type="file" capture="camera" accept="image/*" id="cameraInput" name="cameraInput">

Now, I want to get the image and onchangeevent, convert to base64 and want to show in that page itself.

Kindly help me guys!

ganesh
  • 769
  • 4
  • 11
  • 29
  • 1
    Possible duplicate of [How to access a mobile's camera from a web app?](http://stackoverflow.com/questions/8581081/how-to-access-a-mobiles-camera-from-a-web-app) – Mosh Feu Feb 07 '16 at 13:12
  • Possible duplicate of [How to get base64 encoded data from html image](http://stackoverflow.com/questions/15760764/how-to-get-base64-encoded-data-from-html-image) – Mazzy Feb 07 '16 at 14:07
  • This is not a duplicate, as he wants to display the image on page, presumably without having to upload it first. – Relaxing In Cyprus Sep 11 '16 at 04:26
  • Possible duplicate of [accessing webcam in web pages](http://stackoverflow.com/questions/9533773/accessing-webcam-in-web-pages) – Sarin Jacob Sunny Apr 11 '17 at 12:29
  • Here is an interesting library that does that. [https://github.com/jhuckaby/webcamjs](https://github.com/jhuckaby/webcamjs) – dimshik Feb 07 '16 at 13:36

2 Answers2

9

You can do it like this:

$('#cameraInput').on('change', function(e){
 $data = e.originalEvent.target.files[0];
  $reader = new FileReader();
  reader.onload = function(evt){
  $('#your_img_id').attr('src',evt.target.result);
  reader.readAsDataUrl($data);
}});
Miles Erickson
  • 2,294
  • 1
  • 16
  • 17
Henock Bongi
  • 150
  • 1
  • 11
8

Miles Erickson and Henock Bongi, you need to take reader.readAsDataUrl($data); out of the onload function in order that the onload fire.

If you don't want to use jQuery see below:

function readFile(file) {                                                       
    var reader = new FileReader();
    reader.onload = readSuccess;                                            
    function readSuccess(evt) {     
        document.getElementById("your_img_id").src = evt.target.result                   
    };
    reader.readAsDataURL(file);                                              
} 

document.getElementById('cameraInput').onchange = function(e) {
    readFile(e.srcElement.files[0]);
};
Ana Houa
  • 671
  • 1
  • 7
  • 18
  • 1
    Whats the point in answering a 2 years old post? either way it's better to use URL.createObjectURL instead of using the FileReader – Endless Jan 14 '18 at 19:49
  • 9
    The point is for reference for people like me who take 20 min figuring out why reader.onload is not firring :) – Ana Houa Jan 14 '18 at 21:08
  • Yes you're right i forgot to take it out of onload function. Thanks! – Henock Bongi Oct 25 '18 at 13:12