# How to get the image in the clipboard with a J/Link method?

The Paste will not give a return,just print the content of clipboard.It is hard to asign the result to a variable.I make a .NET method here to get the image in clipboard,but some platform cannot use .NET.So I expect a method based on J/Link.

• If you look in the SETools source, you will find a way to do it with NotebookGet@ClipboardNotebook[]. That is how the "pixel perfect" method works. This is not an answer to your question, because you wanted a J/Link solution. – Szabolcs Mar 31 '17 at 15:49
• Maybe something like First@First@NotebookImport[NotebookGet@ClipboardNotebook[], "Input"], but I have not checked this for robustness. SETools should have a robust version. This also doesn't verify that you actually have an image. – Szabolcs Mar 31 '17 at 15:50
• @Szabolcs Fun,this is my solution:ToExpression[First[FrontEndExecute[FrontEndExportPacket[NotebookGet[ClipboardNotebook[]],"InputText"]]]].I have to confess your version is better than my. – yode Mar 31 '17 at 15:54
• @Szabolcs Oh,note your version cannot process this graphics whose Head is Graphics in clipboard.But my version can. :) – yode Mar 31 '17 at 15:56

It is quite ambitious to extract an image in an arbitrary format from the clipboard using only JLink. This is because the code must anticipate variations such as vector vs. raster format, color models, encodings, and so on. Mathematica's built-in image facilities do a lot of the heavy lifting for us, and I would encourage using a method based upon ClipboardNotebook, or by means of Paste into a temporary hidden notebook (both admittedly awkward methods).

Having said that, here is a quick-and-dirty JLink method to extract a rasterized version of a clipboard image via an intermediate PNG representation:

Needs["JLink"];
InstallJava[];

getClipboardImage[]:=
JavaBlock @ Module[{clipboard, flavor, image, bytes}
, clipboard = javaawtToolkitgetDefaultToolkit[] @ getSystemClipboard[]
; flavor = javaawtdatatransferDataFlavorimageFlavor
; If[!clipboard@isDataFlavorAvailable[flavor], Return[\$Failed]]
; image = clipboard @ getData[flavor]
; bytes = JavaNew["java.io.ByteArrayOutputStream"]
; javaximageioImageIOwrite[image, "PNG", bytes]
; Mod[bytes @ toByteArray[], 256] // FromCharacterCode // ImportString[#, "PNG"]&
]


This code assumes that the clipboard image is represented in Java as a BufferedImage. It would be possible to extend this to support other image types by various means, but those are outside the scope of the present response.

I have tested this successfully on Windows with the usual raster image formats on the clipboard: PNG, GIF, JPEG. I am not in a position to test this code on MacOS or Linux.

• Crazy,man.It's exactly what I want.;)And note my upon comment based on ClipboardNotebook maybe better than your link? – yode Apr 1 '17 at 4:52