我正在嘗試將 PNG 轉換為縮放位圖。最終目標是將影像保持縱橫比縮放為 165 像素的高度。以下代碼作業正常,我得到了我期望的位圖影像,盡管它只將解析度降低了一半并且不計算比例應該是多少:
# Current test file is 256x256
$InFile = '.\someImage.png'
# Read in the initial image as FileStream
[System.IO.FileStream]$imageStream = [System.IO.FileStream]::new(
"$(Resolve-Path $InFile)",
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::Read
)
# Read image FileStream into BitmapSource
$bitmapSource = [System.Windows.Media.Imaging.PngBitmapDecoder]::new(
$imageStream,
[System.Windows.Media.Imaging.BitmapCreateOptions]::PreservePixelFormat,
[System.Windows.Media.Imaging.BitmapCacheOption]::Default
).Frames[0]
$rotatedBitmap = [System.Windows.Media.Imaging.TransformedBitmap]::new(
$bitmapSource,
[System.Windows.Media.RotateTransform]::new(-90)
)
# Scale down the image so it isn't too large
$scale = .5
$scaledBitmap = [System.Windows.Media.Imaging.TransformedBitmap]::new(
$rotatedBitmap,
[System.Windows.Media.ScaleTransform]::new($scale, $scale)
)
# Create new bitmap from rotated/scaled bitmap using BGRA32 pixel format
$convertedBitmap = [System.Windows.Media.Imaging.FormatConvertedBitmap]::new()
$convertedBitmap.BeginInit()
$convertedBitmap.Source = $scaledBitmap
$convertedBitmap.DestinationFormat = [System.Windows.Media.PixelFormats]::Bgra32
$convertedBitmap.EndInit()
# Prepare transformed bitmap for writing via FileStream
$pixels = [byte[]]::new(( $convertedBitmap.PixelWidth * $convertedBitmap.PixelHeight * 4 ))
$stride = $convertedBitmap.PixelWidth * 4 ( $convertedBitmap.PixelWidth % 4 )
$convertedBitmap.CopyPixels($pixels, $stride, 0)
但是,如果我對比例使用不同的值,則會在塊的最后一行出現錯誤。例如,像這樣改變比例:
# Change the $scale = value in the previous code block to this
# for capping the height at 165 pixels and execute to reproduce
$scale = 165 / $rotatedBitmap.PixelHeight
$convertedBitmap.CopyPixels引發錯誤的原因:
Exception calling "CopyPixels" with "3" argument(s): "The parameter value cannot be less than '109064'.
Parameter name: buffer"
At C:\Users\bender\OneDrive\Documents\src\personal\MyProject\Test-Function.ps1:89 char:9
$convertedBitmap.CopyPixels($pixels, $stride, 0)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : ArgumentOutOfRangeException
當我更改縮放比例時,為什么我的代碼會中斷?我最初的研究表明要么$stride是錯誤的,要么是$pixels緩沖區的大小不正確,但我不確定情況如何,因為我從縮放的位圖計算兩者,并且它與其他縮放值一起使用(或完全忽略縮放)。
uj5u.com熱心網友回復:
只需洗掉術語 ( $convertedBitmap.PixelWidth % 4 ). 由于您已將位圖轉換為BGRA32格式,您只需將像素寬度乘以 4 即可根據需要獲得 4 的倍數的步幅(以位元組為單位的寬度):
$stride = $convertedBitmap.PixelWidth * 4
為了完整起見,如果您按原樣使用輸入位圖,因此它可能是 32 以外的其他位深度,則公式應為:
$stride = (((($bitmap.PixelWidth * $bitmap.Format.BitsPerPixel) 31) -band -bnot 31) -shr 3)
不過我還沒有測驗過,我只是將這個檔案中的公式移植到了 powershell。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/505842.html
上一篇:發送到子組件時反應未定義的屬性
