Access raw clipboard PNG image data in Electron (macOS)
Electron provides the API to get clipboard data via clipboard.readImage
.
However, I found it doesn't preserve original image info so some information may drop.
Notably, pHYs
metadata in PNG.
The problem arises when we take a screenshot in macOS with storing it in clipboard, then trying to get the data in Electron.
The width/height is doubled to the original screenshot.
That's due to "scale-factor" mechanism in macOS.
macOS's native apps like Preview.app uses pHYs
information to get the scale-factor, so they can show the image in original size. (See this code for the details)
There's a SO post that discusses same phenomenon.
Workaround
The workaround is to use readBuffer
instead of readImage
to get the unconverted raw image.
readBuffer
takes an argument which specifies the custom format name, and it's passed through to [NSPasteboard dataForType:]
under the hood.
NSPasteboardType
for the raw PNG data in clipboard is defined as NSPasteboardTypePNG
, that is "public.png"
.
Hence, you can access raw PNG data from Electron by readBuffer("public.png")
.
Environment
- Electron: 22.0.3
- macOS: 12.6 (Monterey)