기타
C# Bitmap객체를 8bit gray로 byte array에 담기
카멜레온개발자
2021. 2. 5. 15:36
맞는지 검증은 차차하기로...-_-;
public static byte[] ToGrayscale(Bitmap bmp)
{
int bpp = Image.GetPixelFormatSize(bmp.PixelFormat) / 8;
BitmapData src_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
byte[] src_bytes = new byte[src_data.Stride * src_data.Height];
Marshal.Copy(src_data.Scan0, src_bytes, 0, src_bytes.Length);
// Copy the bytes from the image into a byte array
byte[] dst_bytes = new byte[bmp.Height * bmp.Width];
for(int i=0; i<dst_bytes.Length; ++i)
dst_bytes[i] = (byte)((src_bytes[i * bpp + 0] + src_bytes[i * bpp + 1] + src_bytes[i * bpp + 2]) / 3);
bmp.UnlockBits(src_data);
#if DEBUG
/*
Bitmap result = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format8bppIndexed);
BitmapData dst_data = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
Marshal.Copy(dst_bytes, 0, dst_data.Scan0, dst_bytes.Length);
result.UnlockBits(dst_data);
ColorPalette Palette = result.Palette;
for (int i = 0; i < Palette.Entries.Length; ++i)
{
Palette.Entries[i] = Color.FromArgb(i, i, i);
}
result.Palette = Palette;
result.Save("dst.jpg");
//*/
#endif
return dst_bytes;
}