Learn how to retrieve the clipboard content as an image with JavaScript in the browser.

How to retrieve images from the clipboard with JavaScript in the Browser

As you may know, the manipulation of the clipboard on the web ain't an easy task, not even for plain text and much less for images. The content of the clipboard can't be easily retrieved using a method like clipboard.getContent. If you want to retrieve the images on the most updated browsers (yeah, sorry but' there's no support for IE8) you will need to rely on the paste event of the window:

Note

The event can be only triggered by the user action on the document, namely pressing CTRL+ V.

window.addEventListener("paste", function(thePasteEvent){
    // Use thePasteEvent object here ...
}, false);

When you press CTRL+ V and the current window is focused, this event is triggered. For you is important the thePasteEvent object (parameter received as argument in the callback) that contains the clipboardData object. If the clipboardData object exists, then it will contain the items property (by default undefined if the clipboard is empty):

var items = pasteEvent.clipboardData.items;

Items is an array that contains the data of the clipboard, so you only will need to loop through it. If there's an image on the clipboard, then the content can be converted to a file (Blob) that contains an structure similar to:

{
    name: "image.png", 
    lastModified: 1499172701225, 
    lastModifiedDate: Tue Jul 04 2017 14:51:41 GMT+0200 (W. Europe Daylight Time),
    webkitRelativePath: "", 
    size: 158453,
    type:"image/png",
    webkitRelativePath:""
}

This object is the one you need to retrieve if you want to display the image in the browser or to send it into your server etc. In the methods we'll provide to retrieve easily the image from the clipboard, you will need to provide the thePasteEvent as first argument of the event, otherwise they won't work.

In this article we'll explain how the process to obtain the image from the clipboard works and how to retrieve the image in a Blob or Base64 format.

Retrieve image as Blob

The easiest way to retrieve the image from the clipboard, is with the Blob format (as a file). The following method expects the pasteEvent as first argument and a callback as second argument, that receives as first and unique argument, the blob of the image:

/**
 * This handler retrieves the images from the clipboard as a blob and returns it in a callback.
 * 
 * @param pasteEvent 
 * @param callback 
 */
function retrieveImageFromClipboardAsBlob(pasteEvent, callback){
	if(pasteEvent.clipboardData == false){
        if(typeof(callback) == "function"){
            callback(undefined);
        }
    };

    var items = pasteEvent.clipboardData.items;

    if(items == undefined){
        if(typeof(callback) == "function"){
            callback(undefined);
        }
    };

    for (var i = 0; i < items.length; i++) {
        // Skip content if not image
        if (items[i].type.indexOf("image") == -1) continue;
        // Retrieve image on clipboard as blob
        var blob = items[i].getAsFile();

        if(typeof(callback) == "function"){
            callback(blob);
        }
    }
}

Then it can be used as follows, for example to display the Blob inside a canvas in the document:

<canvas style="border:1px solid grey;" id="mycanvas">

<script>
window.addEventListener("paste", function(e){

    // Handle the event
    retrieveImageFromClipboardAsBlob(e, function(imageBlob){
        // If there's an image, display it in the canvas
        if(imageBlob){
            var canvas = document.getElementById("mycanvas");
            var ctx = canvas.getContext('2d');
            
            // Create an image to render the blob on the canvas
            var img = new Image();

            // Once the image loads, render the img on the canvas
            img.onload = function(){
                // Update dimensions of the canvas with the dimensions of the image
                canvas.width = this.width;
                canvas.height = this.height;

                // Draw the image
                ctx.drawImage(img, 0, 0);
            };

            // Crossbrowser support for URL
            var URLObj = window.URL || window.webkitURL;

            // Creates a DOMString containing a URL representing the object given in the parameter
            // namely the original Blob
            img.src = URLObj.createObjectURL(imageBlob);
        }
    });
}, false);
</script>

Alternatively you can use the Blob as you need, this is just an example.

Retrieve image as base64

By default theĀ retrieveImageFromClipboard method returns a Blob (file-like object of immutable, raw data). As a workaround if you need to retrieve the image with the base64 format, then you can use the following function instead (almost the same as the original) that creates a DOM string from the blob and sets it as source from an image that will be rendered to a canvas. As final step, once the image loads on the abstract canvas (it won't be visible) the callback returns the image in base64 format:

/**
 * This handler retrieves the images from the clipboard as a base64 string and returns it in a callback.
 * 
 * @param pasteEvent 
 * @param callback 
 */
function retrieveImageFromClipboardAsBase64(pasteEvent, callback, imageFormat){
	if(pasteEvent.clipboardData == false){
        if(typeof(callback) == "function"){
            callback(undefined);
        }
    };

    var items = pasteEvent.clipboardData.items;

    if(items == undefined){
        if(typeof(callback) == "function"){
            callback(undefined);
        }
    };

    for (var i = 0; i < items.length; i++) {
        // Skip content if not image
        if (items[i].type.indexOf("image") == -1) continue;
        // Retrieve image on clipboard as blob
        var blob = items[i].getAsFile();

        // Create an abstract canvas and get context
        var mycanvas = document.createElement("canvas");
        var ctx = mycanvas.getContext('2d');
        
        // Create an image
        var img = new Image();

        // Once the image loads, render the img on the canvas
        img.onload = function(){
            // Update dimensions of the canvas with the dimensions of the image
            mycanvas.width = this.width;
            mycanvas.height = this.height;

            // Draw the image
            ctx.drawImage(img, 0, 0);

            // Execute callback with the base64 URI of the image
            if(typeof(callback) == "function"){
                callback(mycanvas.toDataURL(
                    (imageFormat || "image/png")
                ));
            }
        };

        // Crossbrowser support for URL
        var URLObj = window.URL || window.webkitURL;

        // Creates a DOMString containing a URL representing the object given in the parameter
        // namely the original Blob
        img.src = URLObj.createObjectURL(blob);
    }
}

And it can be used as follows:

window.addEventListener("paste", function(e){

    // Handle the event
    retrieveImageFromClipboardAsBase64(e, function(imageDataBase64){
        // If there's an image, open it in the browser as a new window :)
        if(imageDataBase64){
            // data:image/png;base64,iVBORw0KGgoAAAAN......
            window.open(imageDataBase64);
        }
    });
}, false);

Example

Test a live example on the following fiddle:

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors