JavaScript Load Image is a function to load images provided as File or Blob objects or via URL. It returns an optionally scaled HTML img or canvas element.
Include the (minified) JavaScript Load Image script in your HTML markup:
<script src="load-image.min.js"></script>
In your application code, use the loadImage() function like this:
document.getElementById('file-input').onchange = function (e) {
window.loadImage(
e.target.files[0],
function (img) {
document.body.appendChild(img);
},
{width: 600}
);
};
The JavaScript Load Image function has zero dependencies.
However, JavaScript Load Image is a very suitable complement to the Canvas to Blob function.
The loadImage() function accepts a File or Blob object or a simple image URL (e.g. "http://example.org/image.png") as first argument.
If a File or Blob is passed as parameter, it returns a HTML img element if the browser supports the URL API or a FileReader object if supported, or false.
It always returns a HTML img element when passing an image URL:
document.getElementById('file-input').onchange = function (e) {
var loadingImage = window.loadImage(
e.target.files[0],
function (img) {
document.body.appendChild(img);
},
{width: 600}
);
if (!loadingImage) {
// Alternative code ...
}
};
The img element or FileReader object returned by the loadImage() function allows to abort the loading process by setting the onload and onerror event handlers to null:
document.getElementById('file-input').onchange = function (e) {
var loadingImage = window.loadImage(
e.target.files[0],
function (img) {
document.body.appendChild(img);
},
{width: 600}
);
loadingImage.onload = loadingImage.onerror = null;
};
The second argument must be a callback function, which is called when the image has been loaded or an error occurred while loading the image. The callback function is passed one argument, which is either a HTML img element, a canvas element, or an Event object of type "error":
var imageUrl = "http://example.org/image.png";
window.loadImage(
imageUrl,
function (img) {
if(img.type === "error") {
console.log("Error loading image " + imageUrl);
} else {
document.body.appendChild(img);
}
},
{width: 600}
);
The optional third argument is a map of options:
They can be used the following way:
window.loadImage(
fileOrBlobOrUrl,
function (img) {
document.body.appendChild(img);
},
{
width: 600,
height: 300,
crop: true,
upsacel: true,
canvas: true,
noRevoke: true
}
);
All settings are optional. By default, the image is returned as HTML img element without any image size restrictions.
The JavaScript Load Image script is released under the MIT license.