【问题标题】:Resize a Byte Array image in PowerShell在 PowerShell 中调整字节数组图像的大小
【发布时间】:2022-01-22 04:57:25
【问题描述】:

我正在尝试在 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?我相信这应该很容易,但是我花了很长时间试图弄清楚如何将其转换为字节数组并且失败了!

我希望有人能找到我正在寻找的神奇答案:)

【问题讨论】:

  • $Photo = [System.IO.File]::ReadAllBytes("C:\PathToFile\img.jpg")。另外,完成后不要忘记$bmpResized.Dispose()
  • 还可以保存调整大小到 MemoryStream,见:stackoverflow.com/questions/7350679/…

标签: arrays powershell image-processing active-directory


【解决方案1】:

我已经在 C# 中完成了这件事。这在 PowerShell 中实际上是相同的,因为您使用 .NET 类来执行此操作。

你还是会使用.Save,但是to a MemoryStream,然后使用MemoryStream.ToArray(),像这样:

$stream = New-Object System.IO.MemoryStream
$bmpResized.Save($stream, [System.Drawing.Imaging.ImageFormat]::Jpeg)
$byteArray = $stream.ToArray()

这假设您希望所有图像都是 JPEG 格式。

【讨论】:

    【解决方案2】:

    @Theo 已经在 OP 中给出了处理文件的答案。以下是将调整大小的照片保存到 MemoryStream 的示例:

    参见(C# 示例):Convert a bitmap into a byte array

    try {
     $resizedStream = New-Object System.IO.MemoryStream
     $bmpResized.Save($resizedStream, ,$myImageCodecInfo, $encoderParams)
     $resizedPhotoByteArray = $resizedStream.ToArray()
    }
    finally {
     if ($null -ne $resizedStream) {
      $resizedStream.Dispose()
     }
    }
    

    【讨论】:

    • 您的 .Save 行中有一个双逗号。我假设这是一个错字?
    • @GabrielLuci - 谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2011-12-17
    • 2018-11-15
    • 2020-06-27
    • 2013-10-24
    • 2021-04-21
    相关资源
    最近更新 更多