1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
public Bitmap Apply(Bitmap srcImg)
{
if (srcImg.PixelFormat != PixelFormat.Format24bppRgb)
throw new ArgumentException();
// get source image size
int width = srcImg.Width;
int height = srcImg.Height;
// lock source bitmap data
BitmapData srcData = srcImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
// create new grayscale image
Bitmap dstImg = Image.CreateGrayscaleImage(width, height);
// lock destination bitmap data
BitmapData dstData = dstImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
int srcOffset = srcData.Stride - width * 3;
int dstOffset = dstData.Stride - width;
// do the job
unsafe
{
byte* src = (byte*)srcData.Scan0.ToPointer();
byte* dst = (byte*)dstData.Scan0.ToPointer();
// for each line
for (int y = 0; y < height; y++)
{
// for each pixel
for (int x = 0; x < width; x++, src += 3, dst++)
{
*dst = (byte)((src[RGB.R] + src[RGB.G] + src[RGB.B])/3);
}
src += srcOffset;
dst += dstOffset;
}
}
// unlock both images
dstImg.UnlockBits(dstData);
srcImg.UnlockBits(srcData);
return dstImg;
}
} |
Partager