I found a C# method in this SO answer to detect whether or not an image has transparency. I am trying to convert the method to PowerShell.
Unfortunately I can't seem to get it to work. Everything seems to work fine up until the Marshal.Copy part, and all the values are filled properly, except Bytes
array which is full of zeroes even after Marshal.Copy
.
Following is the original code in C#:
public bool IsAlphaBitmap(ref System.Drawing.Imaging.BitmapData BmpData)
{
byte[] Bytes = new byte[BmpData.Height * BmpData.Stride];
Marshal.Copy(BmpData.Scan0, Bytes, 0, Bytes.Length);
for (p = 3; p < Bytes.Length; p += 4) {
if (Bytes[p] != 255) return true;
}
return false;
}
And this is the PowerShell version I have so far (that doesn't work):
function IsAlphaBitMap([string]$imagepath)
{
$BitMap = New-Object System.Drawing.BitMap($imagepath)
$Rect = New-Object System.Drawing.Rectangle(0, 0, $BitMap.Width, $BitMap.Height)
$BmpData = [System.Drawing.Imaging.BitmapData]$BitMap.LockBits($Rect, [System.Drawing.Imaging.ImageLockMode]::ReadWrite, $BitMap.PixelFormat)
$Bytes = New-Object byte[] ($BmpData.Height * $BmpData.Stride)
[System.Runtime.InteropServices.Marshal]::Copy($BmpData.Scan0, $Bytes, 0, $Bytes.Length)
for($p=3 ; $p -lt $Bytes.Length ; $p+=4)
{
if ($Bytes[$p] -ne 255) { write-host $Bytes[$p] } # { return $true }
}
return $false
}
I did use a write-host
in the loop rather than the return value so I that can read the output of each iteration, which is always zero. Can anyone see where I went wrong?