public void InsertMessage(string message) { Stopwatch watch = new Stopwatch(); watch.Start(); var dataToEncode = Encoding.ASCII.GetBytes(message); byte[] dataWithMeta = new byte[dataToEncode.Length + MessageLength + MessageLengthPadding]; //four bytes for message length; 2 bytes for padding var messageLengthInfo = BitConverter.GetBytes(message.Length); Array.Copy(messageLengthInfo, dataWithMeta, MessageLength); Array.Copy(dataToEncode, 0, dataWithMeta, MessageLength + MessageLengthPadding, dataToEncode.Length); BitArray bits = new BitArray(dataWithMeta); var e = bits.GetEnumerator(); var bmpPixelEnumerator = new BitmapPixelEnumerator(_img); foreach (Pixel pixel in bmpPixelEnumerator) { byte oldBlue = pixel.Blue; byte oldGreen = pixel.Green; byte oldRed = pixel.Red; byte newBlue; if (InsertData(e, oldBlue, out newBlue)) return; _copy.SetPixel(pixel.X, pixel.Y, Color.FromArgb(newBlue, oldGreen, oldRed)); byte newGreen; if (InsertData(e, oldGreen, out newGreen)) return; _copy.SetPixel(pixel.X, pixel.Y, Color.FromArgb(newBlue, newGreen, oldRed)); byte newRed; if (InsertData(e, oldRed, out newRed)) return; _copy.SetPixel(pixel.X, pixel.Y, Color.FromArgb(newBlue, newGreen, newRed)); } watch.Stop(); Debug.WriteLine(watch.Elapsed); }
/// <summary> /// Expected 471 length /// </summary> /// <returns></returns> public string ReadMessage() { var bmpPixelEnumerator = new BitmapPixelEnumerator(_img); var encodedLength = bmpPixelEnumerator.Take(PixelsWithMessageLengthAndPadding).ToArray(); int indexLengthBit = 0; var ba = new BitArray(BitsWithMessageLengthAndPadding); foreach (var pixel in encodedLength) { indexLengthBit = ReadTwoBits(pixel.Blue, ba, indexLengthBit); indexLengthBit = ReadTwoBits(pixel.Green, ba, indexLengthBit); indexLengthBit = ReadTwoBits(pixel.Red, ba, indexLengthBit); } var messageLength = ba.ConvertBitsToWord(); int indexMessageBit = 0; var messageBitArray = new BitArray(messageLength * PixelsWithMessageLengthAndPadding); bmpPixelEnumerator.Reset(); var encodedPixels = bmpPixelEnumerator.Skip(PixelsWithMessageLengthAndPadding).Take((int)Math.Ceiling(messageLength * (double)PixelsWithMessageLengthAndPadding / (double)BitsPerPixel)); foreach (var pixel in encodedPixels) { indexMessageBit = ReadTwoBits(pixel.Blue, messageBitArray, indexMessageBit); if (indexMessageBit >= messageBitArray.Count) { break; } indexMessageBit = ReadTwoBits(pixel.Green, messageBitArray, indexMessageBit); if (indexMessageBit >= messageBitArray.Count) { break; } indexMessageBit = ReadTwoBits(pixel.Red, messageBitArray, indexMessageBit); if (indexMessageBit >= messageBitArray.Count) { break; } } byte[] messageBytes = new byte[messageLength]; messageBitArray.CopyTo(messageBytes, 0); var message = Encoding.ASCII.GetString(messageBytes); return message; }