[英]Use PowerShell to save a System.Windows.Interop.InteropBitmap to disk
I would like to use PowerShell to retrieve an image from the Windows clipboard, and save it to a file.我想使用 PowerShell 从 Windows 剪贴板中检索图像,并将其保存到文件中。 When I copy an image to the clipboard, from a web browser for example, I am able to retrieve a
System.Windows.Interop.InteropBitmap
object.例如,当我从 Web 浏览器将图像复制到剪贴板时,我能够检索
System.Windows.Interop.InteropBitmap
对象。 Once I have this object, I need to save the object to disk.一旦我有了这个对象,我需要将对象保存到磁盘。
Question : How can I accomplish this?问题:我怎样才能做到这一点?
Add-Type -AssemblyName PresentationCore
$DataObject = [System.Windows.Clipboard]::GetDataObject()
$DataObject | Get-Member
All credits goes to this answer , this is merely a PowerShell adaptation of that code.所有功劳都归于这个答案,这只是该代码的 PowerShell 改编。
The code consists in 2 functions, one that outputs the InteropBitmap
instance of the image in our clipboard and the other function that receives this object from the pipeline and outputs it to a file.该代码包含 2 个函数,一个在剪贴板中输出图像的
InteropBitmap
实例,另一个函数从管道接收此对象并将其输出到文件。 The Set-ClipboardImage
function can output using 3 different Encoders, you can add more if needed. Set-ClipboardImage
功能可以使用 3 种不同的编码器输出,如果需要,您可以添加更多。 See System.Windows.Media.Imaging
Namespace for details.有关详细信息,请参阅
System.Windows.Media.Imaging
命名空间。
These functions are tested and compatible with Windows PowerShell 5.1 and PowerShell Core.这些函数经过测试并与 Windows PowerShell 5.1 和 PowerShell Core 兼容。 I do not know if this can or will work in prior versions.
我不知道这是否可以或将在以前的版本中工作。
using namespace System.Windows
using namespace System.Windows.Media.Imaging
using namespace System.IO
using namespace System.Windows.Interop
Add-Type -AssemblyName PresentationCore
function Get-ClipboardImage {
$image = [Clipboard]::GetDataObject().GetImage()
do {
Start-Sleep -Milliseconds 200
$downloading = $image.IsDownloading
} while($downloading)
$image
}
function Set-ClipboardImage {
[cmdletbinding()]
param(
[Parameter(Mandatory)]
[ValidateScript({
if(Test-Path (Split-Path $_)) {
return $true
}
throw [ArgumentException]::new(
'Destination folder does not exist.', 'Destination'
)
})]
[string] $Destination,
[Parameter(Mandatory, ValueFromPipeline, DontShow)]
[InteropBitmap] $InputObject,
[Parameter()]
[ValidateSet('Png', 'Bmp', 'Jpeg')]
[string] $Encoding = 'Png'
)
end {
try {
$Destination = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Destination)
$encoder = switch($Encoding) {
Png { [PngBitmapEncoder]::new(); break }
Bmp { [BmpBitmapEncoder]::new(); break }
Jpeg { [JpegBitmapEncoder]::new() }
}
$fs = [File]::Create($Destination)
$encoder.Frames.Add([BitmapFrame]::Create($InputObject))
$encoder.Save($fs)
}
catch {
$PSCmdlet.WriteError($_)
}
finally {
$fs.ForEach('Dispose')
}
}
}
Get-ClipboardImage | Set-ClipboardImage -Destination .\test.jpg -Encoding Jpeg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.