110,545
社区成员
发帖
与我相关
我的任务
分享
//...
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
//...
{
Bitmap bmp = new Bitmap("my.jpg");
// 每一扫描线必须是4 byte的倍数。
int stride = ((bmp.Width - 1) & 0x00FFFFFC) + 4;
byte[] intensities = new byte[ stride * bmp.Height];
// 把计算出来的亮度放到准备好的内存数组中
for(int y = 0; y<bmp.Height; y++)
{
for(int x = 0; x<bmp.Width; x++)
{
Color c = bmp.GetPixel(x,y);
intensities[y * stride + x] = (byte)((c.R + c.G + c.B) / 3);
}
}
// 构置一个8bit的索引图像,直接指定图像数据
GCHandle gch = GCHandle.Alloc(intensities, GCHandleType.Pinned);
Bitmap grayscale = new Bitmap(
bmp.Width,
bmp.Height,
stride,
PixelFormat.Format8bppIndexed,
gch.AddrOfPinnedObject());
gch.Free();
// 重置颜色索引表为灰阶
ColorPalette palette = grayscale.Palette;
for (int i = 0; i < palette.Entries.Length; i++)
{
palette.Entries[i] = Color.FromArgb(i, i, i);
}
grayscale.Palette = palette;
grayscale.Save("gray.bmp");
}