Inserting images from the camera into the document using a WebView

The steps a user follows to insert images into the document are:

  • Tap on a file input button
  • Choose to use the camera roll
  • Read the image
  • Insert the image into the document.

These are the steps. At the moment what is happening in the application I am working on is: in Android when I insert the image, if the image is taken in portrait mode is always inserted into the document as landscape.

Scaffolding the required attributes:
The HTML to start with is a very simple page featuring a file input and a script where all the heavy-lifting will be performed.
The HTML looks like this:


<!doctype html>
<html>
  <head>
    <title>Image from Camera Roll</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <input type="file" id="myfilebutton">
    <script src="camera-roll.js"></script>
  </body>
</html>

What is needed to be done in the script:
We need to:

  • Listen for change events around the file input, allowing only images to be picked up.
  • Read the image off the file input
  • Place the image in the document

To listen to the file input we just need to perform:


var fileInput = document.querySelector('input[type="file"]');  fileInput.addEventListener('change', read, false);

The read function will fire when there is a change in the contents of the file input. At this point we can read the files, if any is attached:


  function read() {
    if (fileInput.files && fileInput.files[0]) {
      var reader = new FileReader();
      reader.onload = function (evt) {
        var img = document.createElement('img');
        img.src = evt.target.result;
        document.body.appendChild(img);
      };
      // Trigger the reading of the file
      reader.readAsDataURL(fileInput.files[0]);    
    }
  }

Note how the file is actually attached to the input and not to the event which has been triggered. This might be confusing since under other circumstances the files are attached to the event, for example in case of a drag and drop.

So far everything is ok, however in Android the image is going to be rotated sideways if the capture is performed in portrait mode. We need to fix this, maybe in another post!