Save Image from clipboard using PowerShell

你说的曾经没有我的故事 提交于 2020-12-11 12:58:17

问题


I am trying to save image from clipboard to the file path. I have tried below script and it is returning "clipboard does not contain image data".

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

As the Clipboard class can only be used in threads set to single thread apartment (STA) mode.

I have tried to run the script in

powershell -NoProfile -Sta -File $file

Also, I have tried to relaunch if runspace is not STA, this didn't help.

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

回答1:


In PowerShell 5.1 you can use Get-clipboard

 get-clipboard -format image
 $img = get-clipboard -format image
 $img.save("c:\temp\temp.jpg")

this should work too:

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://stackoverflow.com/questions/55215482/save-image-from-clipboard-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!