Search code examples
c#visual-studiolsb

C# Changing Least Significant Bit Image Algorithm


I am trying to hide a string of text into a bitmap using the LSB algorithm, which is replacing the least significant bit of the RGB Values for each pixel. So far I have loped through the pixels of the image and cleared the LSB value for each pixel. The part that I am struggling with is inserting the new LSB values that come from a string.

This is what I have done so far any pointers of where to go next would be helpful

string text = txtEncrypt.Text;
//Gets the ascii value of each character from the string
var n = ASCIIEncoding.ASCII.GetBytes(text);

Bitmap myBitmap = new Bitmap(myPictureBox.Image);
byte[] rgbBytes = new byte[0];
int R=0, G=0, B=0;
for (int i = 0; i < myBitmap.Width; i++)
{
    for (int j = 0; j < myBitmap.Height; j++)
    {
        Color pixel = myBitmap.GetPixel(i, j);

        // now, clear the least significant bit (LSB) from each pixel element
        //Therefore Three bits in each pixel spare

        R = pixel.R - pixel.R % 2;
        G = pixel.G - pixel.G % 2;
        B = pixel.B - pixel.B % 2;

        // Need to insert new values
    }
}

Solution

  • Although you can do bit manipulation using "regular" arithmetics (the kind they teach in the first grade) it is more common to use bit manipulation operators to achieve the same goal.

    For example, writing R = pixel.R & ~1 is a lot more common than subtracting pixel.R % 2.

    You don't need to clear the bit before setting it. To force a bit into 1 use R = pixel.R | 1. To force it into zero use the R = pixel.R & ~1 mentioned above.

    To iterate bits of the "messagestored as a sequence ofN` bytes use this check:

    if (message[pos / 8] & (1 << pos % 8) != 0) {
        // bit at position pos is 1
    } else {
        // bit at position pos is 0
    }