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.
1 Answers
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[];
LoadJavaClass["java.awt.Toolkit", AllowShortContext -> False];
LoadJavaClass["java.awt.datatransfer.DataFlavor", AllowShortContext -> False];
LoadJavaClass["javax.imageio.ImageIO", AllowShortContext -> False];
getClipboardImage[]:=
JavaBlock @ Module[{clipboard, flavor, image, bytes}
, clipboard = java`awt`Toolkit`getDefaultToolkit[] @ getSystemClipboard[]
; flavor = java`awt`datatransfer`DataFlavor`imageFlavor
; If[!clipboard@isDataFlavorAvailable[flavor], Return[$Failed]]
; image = clipboard @ getData[flavor]
; bytes = JavaNew["java.io.ByteArrayOutputStream"]
; javax`imageio`ImageIO`write[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
ClipboardNotebookmaybe better than your link? – yode Apr 01 '17 at 04:52
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:49First@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:50ToExpression[First[FrontEndExecute[FrontEnd`ExportPacket[NotebookGet[ClipboardNotebook[]],"InputText"]]]].I have to confess your version is better than my. – yode Mar 31 '17 at 15:54HeadisGraphicsin clipboard.But my version can. :) – yode Mar 31 '17 at 15:56