Click here to Skip to main content
14,393,196 members
Rate this:
Please Sign up or sign in to 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.
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

For that check below mentioned links.

Using the LockBits method to access image data

http://bobpowell.net/lockingbits.aspx[^]

For more info :

http://stackoverflow.com/questions/190385/how-to-manipulate-images-at-pixel-level-in-c[^]

I hope this will help to you.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

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);
                }
                result.AppendLine();
            }
            Console.WriteLine(result);
        }
    }
}

(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,
Fredrik
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100