I am trying to get the pixels a bit faster than one could when using .GetPixel()
but I have found myself that it throws an exception with a 0,0 index with the right LockImageMode
.
Exception
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
public async Task<IList<Color>> GetColorStream( )
{
(_Width, _Height, PixelFormat pixelFormat) = await GetDimensions(_Path);
List<Color> pixels = new();
if (pixelFormat is not PixelFormat.Format32bppRgb or not PixelFormat.Format24bppRgb or not PixelFormat.Format32bppRgb)
throw new InvalidOperationException("Cant operate with ess than 24bpps");
_Data = await GetBitmapData(_Width, _Height, pixelFormat, ImageLockMode.ReadWrite);
if(pixelFormat is PixelFormat.Format24bppRgb or PixelFormat.Format32bppRgb)
{
for (int i = 0; i < _Width; i++)
for (int j = 0; j < _Height; j++)
{
int stride = i * _Data.Stride / 3 + j;
(byte R, byte G, byte B, byte A) = (Marshal.ReadByte(_Data.Scan0, stride), Marshal.ReadByte(_Data.Scan0, stride + 1),
Marshal.ReadByte(_Data.Scan0, stride + 2), 0);
pixels.Add(new Color(R, G, B, A));
}
}
else if(pixelFormat == PixelFormat.Format32bppArgb )
{
for (int i = 0; i < _Width; i++)
for (int j = 0; j < _Height; j++)
{
int stride = i * _Data.Stride / 4 + j;
(byte R, byte G, byte B, byte A) = (Marshal.ReadByte(_Data.Scan0, stride), Marshal.ReadByte(_Data.Scan0, stride + 1),
Marshal.ReadByte(_Data.Scan0, stride + 2), Marshal.ReadByte(_Data.Scan0, stride + 3));
pixels.Add(new Color(R, G, B, A));
}
}
image.UnlockBits(_Data);
image = null;
return pixels;
}```