10

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 Answer 1

13

You can use Get-Clipboard in PowerShell 5.1 or later:

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

Alternatively, accessing internal buffer from ClipBoard.GetDataObject will work:

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"
}
Sign up to request clarification or add additional context in comments.

4 Comments

the second snippet is not working, it throw an error, see: imgur.com/nPDy1Sx
Small optimization for the first snippet: > $img = Get-Clipboard -format image if(!$img) { Write-Host "No File in clipboard." return } $img.save("D:\Temp\temp.jpg")
$img.save("c:\temp\temp.jpg") # It will not be a .jpg file. It will be .png in really.
PowerShell 7's Get-Clipboard does not include a -Format option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.