【问题标题】:Save Image from clipboard using PowerShell使用 PowerShell 从剪贴板保存图像
【发布时间】:2019-03-18 06:13:03
【问题描述】:

我正在尝试将图像从剪贴板保存到文件路径。我试过下面的脚本,它返回“剪贴板不包含图像数据”。

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
}

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    在 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"
    }
    

    【讨论】:

    • 第二个 sn-p 不起作用,它会抛出错误,请参阅:imgur.com/nPDy1Sx
    • 第一个 sn-p 的小优化:> $img = Get-Clipboard -format image if(!$img) { Write-Host "剪贴板中没有文件。"返回 } $img.save("D:\Temp\temp.jpg")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 2010-10-04
    相关资源
    最近更新 更多