110,536
社区成员
发帖
与我相关
我的任务
分享
private static Bitmap BuiltBlackWhiteBitmap(byte[] rawValues, int width, int height)
{
// 新建一个8位灰度位图,并锁定内存区域操作
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format1bppIndexed);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);
// 计算图像参数
int offset = bmpData.Stride - bmpData.Width/8; // 计算每行未用空间字节数
IntPtr ptr = bmpData.Scan0; // 获取首地址
int scanBytes = bmpData.Stride * bmpData.Height; // 图像字节数 = 扫描字节数 * 高度
byte[] grayValues = new byte[scanBytes]; // 为图像数据分配内存
// 为图像数据赋值
int posSrc = 0, posScan = 0; // rawValues和grayValues的索引
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width/8; j++)
{
byte b = 0;
for (int k = 0; k < 8; k++) b = (byte)((b << 1) | (byte)(rawValues[posSrc++] < 96 ? 0 : 1));
grayValues[posScan++] = b;
}
// 跳过图像数据每行未用空间的字节,length = stride - width * bytePerPixel
posScan += offset;
}
// 内存解锁
Marshal.Copy(grayValues, 0, ptr, scanBytes);
bitmap.UnlockBits(bmpData); // 解锁内存区域
//return bitmap;
// 修改生成位图的索引表
ColorPalette palette;
// 获取一个Format8bppIndexed格式图像的Palette对象
using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format1bppIndexed))
{
palette = bmp.Palette;
}
for (int i = 0; i < 2; i++)
{
palette.Entries[i] = Color.FromArgb(i*255, i*255, i*255);
}
// 修改生成位图的索引表
bitmap.Palette = palette;
return bitmap;
}
参数 rawValues 就是 #4 得到的灰度数据 byColorInfo
public Image GetBinaryImage(Image imgSrc, byte byValue) {
Bitmap b = new Bitmap(imgSrc);
Bitmap bmp = b.Clone(new Rectangle(0, 0, imgSrc.Width, imgSrc.Height), PixelFormat.Format24bppRgb);
b.Dispose();
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
byte[] byColorInfo = new byte[bmp.Height * bmpData.Stride];
Marshal.Copy(bmpData.Scan0, byColorInfo, 0, byColorInfo.Length);
byte byR, byG, byB;
for (int x = 0, xLen = bmp.Width; x < xLen; x++) {
for (int y = 0, yLen = bmp.Height; y < yLen; y++) {
byB = byColorInfo[y * bmpData.Stride + x * 3];
byG = byColorInfo[y * bmpData.Stride + x * 3 + 1];
byR = byColorInfo[y * bmpData.Stride + x * 3 + 2];
byte byV = GetAvg(byR, byG, byB);
if (byV >= byValue) {
byV = 255;
} else {
byV = 0;
}
byColorInfo[y * bmpData.Stride + x * 3] =
byColorInfo[y * bmpData.Stride + x * 3 + 1] =
byColorInfo[y * bmpData.Stride + x * 3 + 2] = byV;
}
}
Marshal.Copy(byColorInfo, 0, bmpData.Scan0, byColorInfo.Length);
bmp.UnlockBits(bmpData);
return bmp;
}