Tuesday, January 15, 2013

paste images right into chrome!

OK, this, despite some serious limitations, is right-sexy, "browsers can do that now?" stuff.
I found a page that has a jQuery "image paste" plugin -- it's chrome only, but you can copy an image in an outside program into clipboard and paste it into a DOM element. That will give you a base64-encoded version of the image data that you can then use as as the src to an img tag, or the background-image property of a div. Here's an example! (chrome only)
.

copy image, click here and hit ctrl-v...


result:

The page providing the plugin isn't 100% clear of its use, especially if you're not using CoffeeScript, so here's the upshot:

Obviously you need a reference to the script itself:
<script src="http://kirk.is/m/files/kirkdev/imagepaste/jquery.paste_image_reader.js"></script>

Then in the document ready,call pasteImageReader() on the jQuery selector, and pass in a callback function

    $(".pasteZone").pasteImageReader(loadIt);


That call back function will then be passed a hash. One of the keys of the hash will  "dataURL". You can then use dataURL as the src for an img tag, or as the background-image of a div or somesuch...

$(".pasteImg").attr("src",res.dataURL);
$(".pasteZone").css("backgroundImage", "url("+res.dataURL+")");

That's about it! There are some issues to using Base64-encoded images, like they won't be cached and aren't generally as efficient as external files, but in some circumstances they are darn nifty! This stackoverflow discusses browser compatibility; IE earlier than 8 is out of luck with displaying this type of image. (A simple PHP script or similar could be used to convert a base64 image into a literal file.)

No comments:

Post a Comment