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.
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):
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:
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:
Then it can be used as follows, for example to display the Blob inside a canvas in the document:
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:
And it can be used as follows:
Comments
Post a Comment