Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net.Mime;
- using System.Text;
- using ImageMagick;
- namespace Lab2_4
- {
- public class LSB
- {
- private readonly ushort ONE_BYTE = 8;
- public bool EncodeTextToImage(string text, string path)
- {
- int length = Math.Min(text.Length, 255);
- MagickImage image = null;
- try
- {
- image = new MagickImage(path);
- }
- catch
- {
- return false;
- }
- for (int i = 0; i < ONE_BYTE; i++)
- {
- var pixels = image.GetPixels();
- var color = pixels[i, image.Height - 1].ToColor();
- byte red = color.R;
- red = Convert.ToByte( (red & 254) | ((length & (1 << i)) > 0 ? 1 : 0) );
- var newColors = new MagickColor
- {
- A = color.A,
- B = color.B,
- G = color.G,
- K = color.K,
- R = red
- };
- pixels.SetPixel(new Pixel(i, image.Height - 1, newColors.ToByteArray()));
- }
- int x = ONE_BYTE;
- int y = image.Height - 1;
- for (int i = 0; i < length; i++)
- {
- int character = text[i];
- for (int j = 0; j < ONE_BYTE; j++)
- {
- if (x >= image.Width)
- {
- y--;
- x = 0;
- }
- var pixels = image.GetPixels();
- var color = pixels[x, y].ToColor();
- byte red = color.R;
- red = Convert.ToByte( (red & 254) | ((character & (1 << i)) > 0 ? 1 : 0) );
- var newColors = new MagickColor
- {
- A = color.A,
- B = color.B,
- G = color.G,
- K = color.K,
- R = red
- };
- pixels.SetPixel(new Pixel(i, image.Height - 1, newColors.ToByteArray()));
- x++;
- }
- }
- string[] result_path = path.Split('.');
- result_path[0] = string.Concat(result_path[0], "_resultEncrypting.");
- try
- {
- image.Write(string.Concat(result_path));
- }
- catch
- {
- return false;
- }
- return true;
- }
- public string DecodeTextFromImage(string path)
- {
- var decodedText = string.Empty;
- int length = 0;
- MagickImage image = null;
- try
- {
- image = new MagickImage(path);
- }
- catch
- {
- return null;
- }
- for (int i = 0; i < ONE_BYTE; i++)
- {
- var color = image.GetPixels()[i, image.Height - 1].ToColor();
- length = length | ((color.R & 1) << 1);
- }
- int x = ONE_BYTE;
- int y = image.Height - 1;
- for (int i = 0; i < length; i++)
- {
- int character = 0;
- for (int j = 0; j < ONE_BYTE; j++)
- {
- if (x >= image.Width)
- {
- y--;
- x = 0;
- }
- var color = image.GetPixels()[i, image.Height - 1].ToColor();
- int r = color.R;
- character |= ((r & 1) << j);
- }
- decodedText += Convert.ToChar(character);
- }
- return decodedText;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment