使用PowerShell从剪贴板保存图像

8
我正在尝试将剪贴板中的图像保存到文件路径。我已经尝试了下面的脚本,但它返回了"剪贴板不包含图像数据"的错误信息。
Add-Type -AssemblyName System.Windows.Forms
if ($([System.Windows.Forms.Clipboard]::ContainsImage())) {
    $image = [System.Windows.Forms.Clipboard]::GetImage()
    $filename='e:\test\test.png'         

    [System.Drawing.Bitmap]$image.Save($filename, [System.Drawing.Imaging.ImageFormat]::Png)
    Write-Output "clipboard content saved as $filename"
} else {
    Write-Output "clipboarsd does not contains image data"
}

由于Clipboard类只能在设置为单线程公寓(STA)模式的线程中使用。
我已经尝试在中运行脚本。
powershell -NoProfile -Sta -File $file

另外,我尝试重新启动如果运行空间不是STA,但这并没有帮助。

Add-Type -AssemblyName System.Windows.Forms
if ($host.Runspace.ApartmentState -ne "STA") {
    "Relaunching"
    $file = "./saveImage.ps1"
    powershell -NoProfile -Sta -File $file 
    return
}
1个回答

8
在PowerShell 5.1中,您可以使用Get-clipboard命令。
 get-clipboard -format image
 $img = get-clipboard -format image
 $img.save("c:\temp\temp.jpg")

这也应该可以工作:
Add-Type -AssemblyName System.Windows.Forms
$clipboard = [System.Windows.Forms.Clipboard]::GetDataObject()
if ($clipboard.ContainsImage()) {
    $filename='c:\temp\test3.png'         
    [System.Drawing.Bitmap]$clipboard.getimage().Save($filename, [System.Drawing.Imaging.ImageFormat]::Png)
    Write-Output "clipboard content saved as $filename"
} else {
    Write-Output "clipboard does not contains image data"
}

第二个片段不起作用,它抛出了一个错误,请参见:https://imgur.com/nPDy1Sx - Willis
2
第一段代码的小优化:$img = Get-Clipboard -format image if(!$img) { Write-Host "剪贴板中没有文件。" return } $img.save("D:\Temp\temp.jpg") - pungggi
1
$img.save("c:\temp\temp.jpg") # 它不会是一个 .jpg 文件。实际上它将是一个 .png 文件。 - Garric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接