Next page | Contents page |

Loading & saving images [new March 2019]

It is possible for users to browse for files which JavaScript can display on an HTML page but for security reasons it is not possible to save to files on the user's system. However, as we saw 2 pages back, data can be saved in local storage and retrieved from there.

In writing my own solution to Exercise 14 (previous page) I decided to include browsing for image files to display and then save images in local storage. So the following shows how to do these things.

First we need an input element in the HTML, of type "file":


<label>Image: <input type="file" onchange="getFile (this.files)" accept="image/gif, image/jpeg, image/png"></label>

That presents a button labelled "Browse". When it is clicked a file dialogue is shown, in the operating system's usual style. It allows the user to select one file of any of the types indicated by the accept attribute. The onchange attribute shows that a JavaScript function called getFile will be called.


function getFile (files)
{
  if (files.length) // checks that user did not cancel
  {
    im = new Image ();

    im.onload = function () 
    {
      window.URL.revokeObjectURL (this.src);
      // ... whatever else happens when loaded
    };

    im.src = window.URL.createObjectURL (files [0]); 
  }
}

Note the conversion from file to URL and then releasing it after loading.

The image may then be displayed on a canvas using the usual context.drawImage (im, ...).

Images in local storage

This turns out to be easier than you might imagine because there is no need to use the functions we saw a few pages back, JSON.stringify () and JSON.parse (). The point is that canvas.toDataURL (format) converts the canvas (containing an image) to a string. So storing can be done simply with

	
localStorage.setItem (key, cnv.toDataURL ("image/png"));

and retrieval is also fairly simple:

	
var im = new Image ();

im.onload = function () 
{
  // ... perhaps context.drawImage (im, 0, 0);
};

im.src = localStorage.getItem (key);

My new improved version of grDraw which does all this (and more) can be found at www.grelf.net/grDraw2/grDraw.html.

Next page | Contents page |