C# 更改最低有效位图像算法

C# Changing Least Significant Bit Image Algorithm

我正在尝试使用 LSB 算法将一串文本隐藏到位图中,该算法正在替换每个像素的 RGB 值的最低有效位。到目前为止,我已经遍历了图像的像素并清除了每个像素的 LSB 值。我苦苦挣扎的部分是插入来自字符串的新 LSB 值。

这是我到目前为止所做的任何关于下一步要去哪里的指示都会有所帮助

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
    }
}

按位运算符使这很容易做到:

将最后一位设置为 1:

var newR = pixel.R | 0b00000001

将最后一位设置为 0

var newR = pixel.R & 0b11111110

这是如何工作的: |像 or 运算符那样按字节合并位。和 & 像 and 运算符那样合并位(伪代码):

10101000 | 0000001 = 10101001
10101001 & 1111110 = 10101000

虽然您可以使用 "regular" 算术(他们在一年级教授的那种)进行位操作,但更常见的是使用位操作运算符来实现相同的目标。

例如,写 R = pixel.R & ~1 比减去 pixel.R % 2 更常见。

您无需在设置之前清除该位。要强制进入 1 使用 R = pixel.R | 1。要将其强制为零,请使用上面提到的 R = pixel.R & ~1

要迭代“消息stored as a sequence ofN` 字节的位,请使用此检查:

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