我正在嘗試在 PowerShell 中調整影像大小而不保存臨時檔案,然后將其保存到 Active Directory。
我從資料庫中獲取了一個位元組陣列(我無法控制發送給我的內容),我可以像這樣輕松地將其保存為一個檔案:
[System.Io.File]::WriteAllBytes("C:\PathToFile\img.jpg", $PhotoArray)
我需要做的是調整影像大小,然后更新 Active Directory 中的縮略圖。我可以使用原始檔案執行此操作,因為它已經作為位元組陣列提供給我,如下所示:
Set-ADUser -Identity $UserName -Replace @{thumbnailPhoto=$Photo} -Server $AdServerName
我可以使用以下代碼調整影像大小以使其更小:
$Photo_MemoryStream = new-object System.IO.MemoryStream(,$PhotoAsByteArray)
$quality = 75
$bmp = [system.drawing.Image]::FromStream($Photo_MemoryStream)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[decimal]$canvasWidth = 100.0
[decimal]$canvasHeight = 100.0
$myEncoder = [System.Drawing.Imaging.Encoder]::Quality
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1)
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($myEncoder, $quality)
$myImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|where {$_.MimeType -eq 'image/jpeg'}
$ratioX = $canvasWidth / $bmp.Width;
$ratioY = $canvasHeight / $bmp.Height;
$ratio = $ratioY
if($ratioX -le $ratioY){
$ratio = $ratioX
}
$newWidth = [int] ($bmp.Width*$ratio)
$newHeight = [int] ($bmp.Height*$ratio)
$bmpResized = New-Object System.Drawing.Bitmap($newWidth, $newHeight)
$graph = [System.Drawing.Graphics]::FromImage($bmpResized)
$graph.Clear([System.Drawing.Color]::White)
$graph.DrawImage($bmp,0,0 , $newWidth, $newHeight)
$bmpResized.Save("C:\PathToFile\img.jpg",$myImageCodecInfo, $($encoderParams))
如何將 $bmpResized 轉換為位元組陣列,以便將其插入 Active Directory?我相信這應該很容易,但我花了很長時間試圖弄清楚如何將它轉換為位元組陣列并失敗了!
我希望那里有人有我正在尋找的神奇答案:)
uj5u.com熱心網友回復:
我已經在 C# 中完成了這件事。這在 PowerShell 中確實相同,因為您使用 .NET 類來執行此操作。
你仍然會使用.Save, 但到 aMemoryStream,然后使用MemoryStream.ToArray(),像這樣:
$stream = New-Object System.IO.MemoryStream
$bmpResized.Save($stream, [System.Drawing.Imaging.ImageFormat]::Jpeg)
$byteArray = $stream.ToArray()
這假設您需要 JPEG 格式的所有影像。
uj5u.com熱心網友回復:
@Theo 已經在 OP 中給出了處理檔案的答案。以下是將調整大小的照片保存到 MemoryStream 的示例:
請參閱(C# 示例):將位圖轉換為位元組陣列
try {
$resizedStream = New-Object System.IO.MemoryStream
$bmpResized.Save($resizedStream, ,$myImageCodecInfo, $encoderParams)
$resizedPhotoByteArray = $resizedStream.ToArray()
}
finally {
if ($null -ne $resizedStream) {
$resizedStream.Dispose()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388241.html
上一篇:CSV將單元格值與當前時間匹配
下一篇:使用格式將列添加到CSV
