Answer the question
In order to leave comments, you need to log in
How do pointers affect the speed of the method for reading color from a bitmap?
Please tell me, to understand: why this method for reading color from a bitmap
public unsafe static byte[, ,] BitmapToByteRgb(Bitmap bmp)
{
int width = bmp.Width,
height = bmp.Height;
byte[, ,] res = new byte[3, height, width];
BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
try
{
byte* curpos;
for (int h = 0; h < height; h++)
{
curpos = ((byte*)bd.Scan0) + h * bd.Stride;
for (int w = 0; w < width; w++)
{
res[2, h, w] = *(curpos++);
res[1, h, w] = *(curpos++);
res[0, h, w] = *(curpos++);
}
}
}
finally
{
bmp.UnlockBits(bd);
}
return res;
}
public static byte[, ,] BitmapToByteRgbNaive(Bitmap bmp)
{
int width = bmp.Width,
height = bmp.Height;
byte[, ,] res = new byte[3, height, width];
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
Color color = bmp.GetPixel(x, y);
res[0, y, x] = color.R;
res[1, y, x] = color.G;
res[2, y, x] = color.B;
}
}
return res;
}
Answer the question
In order to leave comments, you need to log in
So they influence that you write / read directly to the memory, which will then be used by the Bitmap for drawing / saving and everything else. In particular, you don't have GetPixel/SetPixel calls, which are VERY SLOW for this task. You have a loop in two dimensions of the picture, i.e. calls to GetPixel will be width * height pieces. Believe me, it's a lot and hard. Address arithmetic, namely
much easier. Actually, the possibility of its use is provided by blocking the real data of the bitmap using the LockBits method. A lock here means a mark for the CLR code, in particular for the GC, that this area of \u200b\u200bmemory cannot be touched (moved, for example) until you remove this mark.
Strictly speaking, more or less fast work with Bitmap is possible only through BitmapData, since using Get/SetPixel you will not wait until the end of your algorithm.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question