Вопрос

I had a question related to the use of Lockbits method in C#.. I have a 1bpp Image and I'm trying to access all the pixels of the image but some are still left out.

    public Bitmap Pixels(Bitmap original)
        {
    Rectangle rect = new Rectangle(0, 0, original.Width, original.Height);
                BitmapData bimgData = original.LockBits(rect, ImageLockMode.ReadWrite, original.PixelFormat);

            IntPtr ptr = bimgData.Scan0;

            int bytes = bimgData.Stride * bimg.Height;
            byte[] Values = new byte[bytes];

            Marshal.Copy(ptr, Values, 0, bytes);

            int Val;
            int stride = bimgData.Stride;
for (int column = 0; column < bimgData.Height; column = column + 1)
                    for (int row = 0; row < bimgData.Width; row = row +1)
                    {
                        c = column;
                        r = row;
                        for (int t = 0; t < 8; t++)
                        {
                           Val = Values[((c) * stride) + ((r) / 8)] & 2 ^ t;
                           if (Val == 0)
                                Values[((c) * stride) + ((r) / 8)] = (byte)(Values[((c) * stride) + ((r) / 8)] + 2 ^ t);
                        }
                    }
Marshal.Copy(Values, 0, ptr, bytes);
            original.UnlockBits(bimgData);

            return original;
        }

This code should turn all the pixels white

Это было полезно?

Решение

   Val = Values[((c) * stride) + ((r) / 8)] & 2 ^ t;

2 ^ t doesn't do what you hope it does, that's Visual Basic syntax. In the C# language, ^ is the XOR operator. Use the << operator instead and use parentheses to take care of operator precedence. Fix:

   Val = Values[((c) * stride) + ((r) / 8)] & (1 << t);

And fix it again when you set the bit.

Do note that turning the entire image to White doesn't require this kind of code at all. Just set all the bytes to 0xff.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top