Fixing right click → copy image function in plugin

update 9/5/21: :rocket: new version of the plugin with the copy image function from this PR has been posted! see here.


I’m trying to bang away again at fixing the Right Click → Copy image function from my fork of NomarCub’s obsidian-copy-url-in-preview plugin.

I know I need to assemble a NativeImage object to write it to the clipboard with clipboard.writeImage(image)

Does any kind soul know how I might access the contents.copyImageAt(x, y) function from within a plugin? It seems from reading the webContents docs that I need to import BrowserWindow but I don’t know how to access the contents. object for the view that Obsidian has already created.

The “solution” I came up with before was to grab the properties of the clicked element and literally read the file from disk or re-download the image again… embarrassingly inefficient and obviously doesn’t work if you’re offline or the webserver has died

There must be a way to just copy the blob / base64 image data off the canvas and shove it into the clipboard without reaching out to the filesystem or making http requests…

Can anyone help? :worried:

Another thought is to create a new (hidden) BrowserWindow instance so I could get at the image element directly via webContents API. Not sure if this is the “right” approach? @Licat any guidance would be immensely appreciated.

You can just use require('electron').nativeImage.createFromBuffer no?

If that’s possible, it’s news to me… how would you obtain the handle to the Buffer from the event emitted by the MouseEvent?

(P.S. thanks for the reply)

The buffer would be the image data you’re trying to copy - you might need to convert from a browser Uint8Array/ArrayBuffer to a node Buffer object using Buffer.from(arrayBuffer), where the arrayBuffer is what you get from vault.readBinary(file).

Thanks @Licat

But what if the image is not a local vault image e.g. ![](https://xyz.com/foo.png) ?

I have just tested @sissilab’s solution from Suggestion: copy image from ViewContainer · Issue #4 · sissilab/obsidian-image-toolkit · GitHub and it works!

I just need to rework a few things and I’ll be pushing an updated PR to @NomarCub’s plugin tomorrow.

Rewritten version has been posted: https://github.com/NomarCub/obsidian-copy-url-in-preview/pull/3

If anyone wants to kick the tires on this before it gets merged, here’s a precompiled main.js you can drop in:

main.js

PR was merged, and the new functionality is available in v1.1.0 via the main community plugins repo.