Skip to main content

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 CTRLV.

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

When you press CTRLV 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 clipboardDataobject 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);

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...