将24bpp位图转换为1bpp

本文关键字:1bpp 转换 位图 24bpp | 更新日期: 2023-09-27 18:03:04

我正在尝试转换一个小位图图像。我希望将任何不是100%白色的像素转换为黑色。我试过了

Bitmap output = sourceImage.Clone(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), PixelFormat.Format1bppIndexed);

在1bpp输出中仍然有一些较轻的像素保持白色。实现这种转化的最快方式是什么?我可以修改Clone()调用的强度阈值吗?

将24bpp位图转换为1bpp

试试这个,从非常快速的1bpp转换:

从这里复制图像到1bpp时的阈值?

        private static unsafe void Convert(Bitmap src, Bitmap conv)
        {
            // Lock source and destination in memory for unsafe access
            var bmbo = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadOnly,
                                     src.PixelFormat);
            var bmdn = conv.LockBits(new Rectangle(0, 0, conv.Width, conv.Height), ImageLockMode.ReadWrite,
                                     conv.PixelFormat);
            var srcScan0 = bmbo.Scan0;
            var convScan0 = bmdn.Scan0;
            var srcStride = bmbo.Stride;
            var convStride = bmdn.Stride;
            byte* sourcePixels = (byte*)(void*)srcScan0;
            byte* destPixels = (byte*)(void*)convScan0;
            var srcLineIdx = 0;
            var convLineIdx = 0;
            var hmax = src.Height-1;
            var wmax = src.Width-1;
            for (int y = 0; y < hmax; y++)
            {
                // find indexes for source/destination lines
                // use addition, not multiplication?
                srcLineIdx += srcStride;
                convLineIdx += convStride;
                var srcIdx = srcLineIdx;
                for (int x = 0; x < wmax; x++)
                {
                    // index for source pixel (32bbp, rgba format)
                    srcIdx += 4;
                    //var r = pixel[2];
                    //var g = pixel[1];
                    //var b = pixel[0];
                    // could just check directly?
                    //if (Color.FromArgb(r,g,b).GetBrightness() > 0.01f)
                    if (!(sourcePixels[srcIdx] == 0 && sourcePixels[srcIdx + 1] == 0 && sourcePixels[srcIdx + 2] == 0))
                    {
                        // destination byte for pixel (1bpp, ie 8pixels per byte)
                        var idx = convLineIdx + (x >> 3);
                        // mask out pixel bit in destination byte
                        destPixels[idx] |= (byte)(0x80 >> (x & 0x7));
                    }
                }
            }
            src.UnlockBits(bmbo);
            conv.UnlockBits(bmdn);
        }