If u want to use pointer in c# u have to use “unsafe” keyword. and then we can use byte pointer. In BitmapData we Can get data as a byte in different format. In my first
Bitmap pbmp=new Bitmap("fillocation");
int r = 0;
int g = 0;
int b = 0;
int a = 0;
BitmapData data = pbmp.LockBits(new Rectangle(0, 0, pbmp.Width, pbmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
byte* imgPtr = (byte*)(data.Scan0);
pbmp.UnlockBits(data);
for (int x = 0; x < pbmp.Width; x++)
{
for (int y = 0; y < pbmp.Height; y++)
{
a = (int)*imgPtr;
imgPtr++;
r = (int)*imgPtr;
imgPtr++;
g = (int)*imgPtr;
imgPtr++;
b = (int)*imgPtr;
imgPtr++;
}
imgPtr += data.Stride - pbmp.Height * 4;
}
example u can see i use
PixelFormat.Format32bppArgb
as bitmap data. So every pixel data come in 4 byte first byte contain alpha value, then sequencely red , green and blue value.
byte* imgPtr = (byte*)(data.Scan0);
here the first byte of image pointed by the pointer imgptr.
then we start two loop in innar loop every byte continously represent alpha, red , green, blue, alpha red, green , blue……………………….. values of pixel. To jump out second line first pixel we used
imgPtr += data.Stride - pbmp.Height* 4;
here it was multiply by 4 because of our pixelformat was “PixelFormat.Format32bppArgb”.
now if u want to take 4 bytes in a value name color u can use this code
BitmapData data = pbmp.LockBits(new Rectangle(0, 0, pbmp.Width, pbmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); byte* imgPtr = (byte*)(data.Scan0); pbmp.UnlockBits(data); for (int x = 0; x < pbmp.Width; x++) { for (int y = 0; y < pbmp.Height; y++) {
Color c = Color.FromArgb((int)*imgPtr);imgPtr=
imgPtr+4
; } imgPtr += data.Stride - pbmp.Height * 4; }
Now if u use another pixelformat like “PixelFormat.Format24bppRgb” where only Red, green and blue present u code will change as
Bitmap pbmp=new Bitmap("fillocation"); int r = 0; int g = 0; int b = 0; BitmapData data = pbmp.LockBits(new Rectangle(0, 0, pbmp.Width, pbmp.Height), ImageLockMode.ReadWrite, PixelFormat.
Format24bppRgb); byte* imgPtr = (byte*)(data.Scan0); pbmp.UnlockBits(data); for (int x = 0; x < pbmp.Width; x++) { for (int y = 0; y < pbmp.Height; y++) { r = (int)*imgPtr; imgPtr++; g = (int)*imgPtr; imgPtr++; b = (int)*imgPtr; imgPtr++; } imgPtr += data.Stride - pbmp.Height * 3; }
So for different type of pixel format u have to try differnt calculation for byte pointer.
and if are not familiar with how to use byte pointer just write ur function like that,
private unsafe Color pointerimagefunc(Bitmap pbmp){.........}
and make sure in ur build properties allow unsafe code is checked