如何让Windows 10 PowerShell读取剪贴板图片时保留透明度信息?
问题描述
我尝试用Windows 10 PowerShell将带透明背景的PNG图片转换为白色背景的不透明图片,原图片是网页图表,目标是复制粘贴到Excel中。用维基百科透明logo复现问题:
下载图片后,PowerShell读取结果如下:
PS C:\Users\test\Desktop> New-Object System.Drawing.Bitmap("526px-Wikipedia-logo-transparent.png") Tag : PhysicalDimension : {Width=526, Height=480} Size : {Width=526, Height=480} Width : 526 Height : 480 HorizontalResolution : 96 VerticalResolution : 96 Flags : 73746 RawFormat : [ImageFormat: b96b3caf-0728-11d3-9d7b-0000f81ef32e] PixelFormat : Format32bppArgb Palette : System.Drawing.Imaging.ColorPalette FrameDimensionsList : {7462dc86-6180-4c7e-8e3f-ee7333a7a483} PropertyIdList : {769, 318, 319, 306...} PropertyItems : {769, 318, 319, 306...}
可见PixelFormat明确支持Alpha通道。
但从浏览器复制同一张图片后,PowerShell读取剪贴板内容时Alpha通道消失:
PS C:\Users\test\Desktop> Get-Clipboard -Format image Tag : PhysicalDimension : {Width=526, Height=480} Size : {Width=526, Height=480} Width : 526 Height : 480 HorizontalResolution : 96 VerticalResolution : 96 Flags : 335888 RawFormat : [ImageFormat: b96b3caa-0728-11d3-9d7b-0000f81ef32e] PixelFormat : Format32bppRgb Palette : System.Drawing.Imaging.ColorPalette FrameDimensionsList : {7462dc86-6180-4c7e-8e3f-ee7333a7a483} PropertyIdList : {} PropertyItems : {}
另外,将图片导入Paint 3D后复制到剪贴板,无论“透明画布”是否开启,PowerShell读取时都无透明度信息,但粘贴到Excel时,“透明画布”状态会影响结果——说明剪贴板携带了透明度信息,但PowerShell默认读取方式无法识别。
需求:如何让PowerShell处理带透明度信息的图片?仅允许使用Windows标准工具,禁止第三方工具。
解决方案
1. 读取剪贴板中的原始透明图片
Get-Clipboard -Format image会自动将图片转换为无Alpha通道的格式,改用.NET的System.Windows.Forms.Clipboard类可以读取保留Alpha通道的原始图像数据:
# 加载Windows Forms和Drawing程序集 Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing # 检查剪贴板是否包含图像 if ([System.Windows.Forms.Clipboard]::ContainsImage()) { # 获取带Alpha通道的图像对象 $originalImage = [System.Windows.Forms.Clipboard]::GetImage() # 验证格式 Write-Host "读取到的图像格式: $($originalImage.PixelFormat)" } else { Write-Host "剪贴板中无图像数据" }
2. 将透明背景转为白色背景
拿到带Alpha通道的图像后,通过绘制到白色背景的新画布完成转换:
# 创建与原图尺寸一致的新Bitmap,默认透明背景 $newBitmap = New-Object System.Drawing.Bitmap($originalImage.Width, $originalImage.Height) $graphics = [System.Drawing.Graphics]::FromImage($newBitmap) # 填充白色背景 $graphics.Clear([System.Drawing.Color]::White) # 绘制原始图像(Alpha通道会自动合成到白色背景) $graphics.DrawImage($originalImage, 0, 0) # 可选:保存到本地 $newBitmap.Save("C:\Users\test\Desktop\white-bg-image.png", [System.Drawing.Imaging.ImageFormat]::Png) # 释放资源 $graphics.Dispose() $originalImage.Dispose() $newBitmap.Dispose()
3. 直接将转换后的图片写入剪贴板
如果不需要保存本地,直接生成后写入剪贴板供Excel粘贴:
Add-Type -AssemblyName System.Windows.Forms # 假设$newBitmap是转换后的图像对象 [System.Windows.Forms.Clipboard]::SetImage($newBitmap)
关键说明
- PowerShell的
Get-Clipboard -Format image会优先选择剪贴板中的无Alpha格式数据,而System.Windows.Forms.Clipboard::GetImage()会读取保留Alpha通道的原始图像格式。 - Paint 3D复制到剪贴板的图片会同时携带多种格式,上述方法可以正确识别其中的透明格式。
内容的提问来源于stack exchange,提问作者Horst Meier
相关产品推荐
相关产品推荐

