Click here to Skip to main content
15,035,283 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
i have an Image object. it's monochrome. i need to get pixels of the image and save each adjacent 8 pixels as a byte.
how can i do it in C#?
for example if the eight pixels from top left of image are white, white, black, black, black, white, white and black i want to write value 0x39 in the output file.

For that check below mentioned links.

Using the LockBits method to access image data[^]

For more info :[^]

I hope this will help to you.
Something like this might solve it for you.

using System.Drawing;
using System.Text;
using System;

namespace ParseTest
    internal class Program
        private const int Black = unchecked((int)0xFF000000);
        private const int White = unchecked((int)0xFFFFFFFF);

        private static bool IsValid(Color pixel)
            var argb = pixel.ToArgb();
            return argb == Black || argb == White;

        private static int GetBlackBit(Color pixel) {
            var argb = pixel.ToArgb();
            return argb == Black ? 1 : 0;

        static void Main()
            var image = (Bitmap)Image.FromFile(@"C:\Temp\Input.png");
            var result = new StringBuilder();

            for (var y = 0; y < image.Size.Height; ++y)

                for (var x = 0; x < image.Size.Width; x += 8)
                    var value = 0;
                    for (var i = 0; i < 8; ++i)
                        var pixel = image.GetPixel(x + i, y);
                        if (!IsValid(pixel))
                            throw new Exception("Image is not monochrome!!!");

                        value |= GetBlackBit(pixel) << (7 - i);
                    result.AppendFormat("0x{0:X2} ", value);

(note that the example only works on images with a width that is a multiple of 8).

Note that you might get a performance boost from locking the bits and getting the data directly, but using pointers means you need to mark your code as unsafe.

Hope this helps,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900