Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public enum State
- {
- Hiding,
- FillingWithZeros
- };
- public static Bitmap EmbedText(string text, Bitmap bmp)
- {
- // save to png, don't save to lossy image formats like jpeg
- State state = State.Hiding;
- int charIndex = 0;
- int charValue = 0;
- long pixelElementIndex = 0;
- int zeros = 0;
- int R = 0, G = 0, B = 0;
- for (int i = 0; i < bmp.Height; i++)
- {
- for (int j = 0; j < bmp.Width; j++)
- {
- Color pixel = bmp.GetPixel(j, i);
- // clear the least significant bit (LSB) from each pixel element
- R = pixel.R - pixel.R % 2;
- G = pixel.G - pixel.G % 2;
- B = pixel.B - pixel.B % 2;
- for (int n = 0; n < 3; n++)
- {
- if (pixelElementIndex % 8 == 0)
- {
- // we can say that it's finished when 8 zeros are added
- if (state == State.FillingWithZeros && zeros == 8)
- {
- if ((pixelElementIndex - 1) % 3 < 2)
- {
- bmp.SetPixel(j, i, Color.FromArgb(R, G, B));
- }
- return bmp;
- }
- if (charIndex >= text.Length)
- {
- state = State.FillingWithZeros;
- }
- else
- {
- charValue = text[charIndex++];
- }
- }
- if (pixelElementIndex % 3 == 0)
- {
- {
- if (state == State.Hiding)
- {
- R += charValue % 2;
- charValue /= 2;
- }
- }
- }
- else if (pixelElementIndex % 3 == 1)
- {
- {
- if (state == State.Hiding)
- {
- G += charValue % 2;
- charValue /= 2;
- }
- }
- }
- else if (pixelElementIndex % 3 == 2)
- {
- {
- if (state == State.Hiding)
- {
- B += charValue % 2;
- charValue /= 2;
- }
- bmp.SetPixel(j, i, Color.FromArgb(R, G, B));
- }
- }
- pixelElementIndex++;
- if (state == State.FillingWithZeros)
- {
- zeros++;
- }
- }
- }
- }
- return bmp;
- }
- public static string ExtractText(Bitmap bmp)
- {
- int colorUnitIndex = 0;
- int charValue = 0;
- string extractedText = String.Empty;
- for (int i = 0; i < bmp.Height; i++)
- {
- for (int j = 0; j < bmp.Width; j++)
- {
- Color pixel = bmp.GetPixel(j, i);
- for (int n = 0; n < 3; n++)
- {
- if (colorUnitIndex % 3 == 0)
- {
- {
- charValue = charValue * 2 + pixel.R % 2;
- }
- }
- else if (colorUnitIndex % 3 == 1)
- {
- {
- charValue = charValue * 2 + pixel.G % 2;
- }
- }
- else if (colorUnitIndex % 3 == 2)
- {
- {
- charValue = charValue * 2 + pixel.B % 2;
- }
- }
- colorUnitIndex++;
- if (colorUnitIndex % 8 == 0)
- {
- charValue = ReverseBits(charValue);
- // can only be 0 if it is the stop character (the 8 zeros)
- if (charValue == 0)
- {
- return extractedText;
- }
- char c = (char)charValue;
- extractedText += c.ToString();
- }
- }
- }
- }
- return extractedText;
- }
- private static int ReverseBits(int n)
- {
- int result = 0;
- for (int i = 0; i < 8; i++)
- {
- result = result * 2 + n % 2;
- n /= 2;
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement