Skip to content

Instantly share code, notes, and snippets.

@fangbinwei
Last active May 18, 2020 03:51
Show Gist options
  • Save fangbinwei/fa960ff7f634a3112c42d127382f2b72 to your computer and use it in GitHub Desktop.
Save fangbinwei/fa960ff7f634a3112c42d127382f2b72 to your computer and use it in GitHub Desktop.
get clipboard image on windows
const execa = require('execa')
const path = require('path')
const fs = require('fs')
async function main() {
const scriptPath = path.join(__dirname, 'pc.ps1');
const imagePath = path.resolve(__dirname, 'clipboard.png')
try {
let command = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
command = fs.existsSync(command) ? command : 'powershell'
const { stdout } = await execa(command, [
'-noprofile',
'-noninteractive',
'-nologo',
'-sta',
'-executionpolicy', 'unrestricted',
'-windowstyle', 'hidden',
'-file', scriptPath,
imagePath
], {
});
return {
noImage: stdout === 'no image',
fsPath: stdout
}
} catch (err) {
if (err.code === 'ENOENT') {
console.error('Failed to execute powershell')
}
}
}
main()
param($imagePath)
# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1
Add-Type -Assembly PresentationCore
$img = [Windows.Clipboard]::GetImage()
if ($img -eq $null) {
"no image"
Exit
}
if (-not $imagePath) {
"no image"
Exit
}
$fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)
$stream = [IO.File]::Open($imagePath, "OpenOrCreate")
$encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder
$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null
$encoder.Save($stream) | out-null
$stream.Dispose() | out-null
$imagePath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment