Paste Image From Clipboard With Javascript and MooTools

2012
23
March
12:13 pm

Images and text can be loaded from the user’s clipboard. For this example we will be focusing on loading an image from the clipboard.

Please note, this is for loading image data (i.e. right clicking an image within the browser and selecting copy, or taking a screenshot (to clipboard)) and not for loading copied files. (i.e. copying from the desktop) – That is stored in an entirely different place.

First, we use the paste event to capture when the user pastes to the page.

window.addEvent("paste",function(e){ });

We then need to cycle through the clipboard data items.

Array.each(e.event.clipboardData.items,function(item){ });

The image data must then be converted to a local URL to be used within the client-side scripting

var blob = item.getAsFile();
var URL = window.URL || window.webkitURL;
var source = URL.createObjectURL(blob);

Code

window.addEvent('domready', function() {
$(window).addEvent("paste",function(e){
   if (e.event.clipboardData) {
       
       Array.each(e.event.clipboardData.items,function(item){
        if (item.type.indexOf("image") !== -1) {
           var blob = item.getAsFile();
           var URL = window.URL || window.webkitURL;
           var source = URL.createObjectURL(blob);

            $("MyImageDataLoadDemo").set("src",source);
           
        }
      });
   }
});
});
​
<div id="imgHold"><img src="" id="MyImageDataLoadDemo"/></div> <div>Click on the area above and ctrl+p an image to paste</div>
Posted in: Development
Tagged with:
Download
Source

Comments

  1. Demo is not working… but your concept is too good… can u show me the working model of your concept…..

Leave a Reply to Shaify Mehta Cancel reply

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