12 Jun

JavaScript image preview snippet

Code for custom JavaScript Image Upload Preview from a file input field.

JavaScript image preview

Time for another coding snippet – this time a JavaScript image preview. Several months ago, I was working on an trivia-like web-app. I needed to allow users to create their own trivia games and share them on social networks, and challenge their friends. Unlike many other trivia website, this one allows for games to actually look like games, meaning have an image representation of the game. This lead to creating an file input field, allowing game creators to actually upload their own image. Now, since the app is actually scaling and cropping the image, I had to come up with a way for game creator to see the image preview before the upload. Obviously, I needed my very own javascript image preview script, and here’s what I came up with.

HTML part

First and foremost – we need some HTML. I’ve simply created label and file input elements.

<label for="cover">
    <span>Upload game cover…</span>
    <input type="file" id="cover" name="cover" onchange="getPreview(this)">
</label>
<div id="preview-image"></div>

Notice that I wrapped the whole code with label tag. This is so that it would automatically prompt you to pick an image upon clicking. This pure HTML trick served me well numerous times. onChange event is on the input tag is fired on selecting the image for upload. Line 4: simple empty div tag as our preview image holder.

JavaScript

Now, we needed an method to wrap up all other methods involved. In this case, it’s a getPreview() function.

function getPreview(file) {
    resizeImage(file.files[0]).then(function (cover) {
        var cpreview = document.getElementById("preview-image");
        cpreview.setAttribute('style','background-image: url(\'' + cover + '\'); background-size: contain;');
    });
}

And now, onto the hard part: resizing the image.

function resizeImage(file) {
    return new Promise(function (a) {
        // Create an image
        var img = document.createElement("img");

        // Create a file reader
        var reader = new FileReader();
        // Set the image once loaded into file reader

        var ready = false;

        reader.onload = function (e) {
            img.src = e.target.result;
            img.onload = function () {

                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                
                ctx.drawImage(img, 0, 0);

                var width = img.width;
                var height = img.height;

                var canvasRatio = 0.75;
                var ratio = img.height / img.width;

                if (ratio < canvasRatio) {
                    img.width = width * 600 / height;
                    img.height = 600;
                }
                else {
                    img.height = height * 800 / width;
                    img.width = 800;
                }

                canvas.width = 800;
                canvas.height = 600;

                ctx.drawImage(img,
                    400 - img.width / 2,
                    300 - img.height / 2,
                    img.width,
                    img.height
                );

                var dataurl = canvas.toDataURL('image/jpeg', 1.0);
                ready = true;
                a(dataurl);
            }
        }

        reader.readAsDataURL(file);
    })
}

A few notes on this method, which I believe are really !important. 😉 First one, make sure you always use promises. This way, you can kind of overcome the JavaScripts native asynchronous nature. For the purpose of this JavaScript image preview snippet, I’ve set my desired image size to 600×800, which you should change per your needs.

Simply enough: resize the image, and set the its base64 representation as backround-image source for preview div. Feel free to comment on my JavaScript image preview snippet.

Follow musingmick and share content:

Leave a Reply

Your email address will not be published. Required fields are marked *

Spread the word