Перевод из двоичного кода в текст - C#
Формулировка задачи:
Добрый день, в c# совсем новичок, занимаюсь стеганографией. Почти все сделал только немного не понимаю как раскодировать. Сначала я заливаю картинку, затем пишу сообщение. Это сообщение перевожу в двоичный код. Посредством измены последнего пикселя я меняю последний бит пиксиля на тот, который у меня в сообщении. Делаю с [0,0] пикселя и до последнего, посредством i++ и j++ в циклах. В дешифровке забираю свое сообщение в двоичном коде, которое в string'е. и что делать дальше не знаю. К примеру, string s = "10101010101010101101001010101010", прошу помочь, буду очень благодарен.
Решение задачи: «Перевод из двоичного кода в текст»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace New_Steg
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button3_Click(object sender, EventArgs e)
- {
- OpenFileDialog openDialog = new OpenFileDialog();
- openDialog.Filter = "Image Files (*.png, *.jpg) | *.png; *.jpg";
- openDialog.InitialDirectory = @"C:\\Users\Desktop";
- if (openDialog.ShowDialog() == DialogResult.OK)
- {
- textBoxFilePath.Text = openDialog.FileName.ToString();
- pictureBox1.ImageLocation = textBoxFilePath.Text;
- }
- }
- private void button1_Click(object sender, EventArgs e) // кнопка кодирования
- {
- Bitmap img = new Bitmap(textBoxFilePath.Text);
- int m = 0; //счетчик
- string mess = "";
- for (int i=0;i<textBoxMessage.TextLength;i++)
- {
- char letter = Convert.ToChar(textBoxMessage.Text.Substring(i, 1));
- byte b_letter = Convert.ToByte(letter);
- mess += Convert.ToString(b_letter, 2);
- } //конвертация текста в двоичный код
- Console.WriteLine("all letters " + mess);
- for (int i = 0; i < img.Width; i++)
- {
- for (int j = 0; j < img.Height; j++)
- {
- Color pixel = img.GetPixel(i, j);
- byte b_pixel = Convert.ToByte(pixel.B); // получение кода синего пикселя
- if (m <mess.Length)
- {
- img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, code(b_pixel,mess.Substring(m,1))));
- Console.WriteLine("i " + i + " j " + j+ " bytes: "+ b_pixel+" mess_1 "+mess.Substring(m, 1));
- m++;
- } // изменяет голубой бит пикселя
- if (i == img.Width - 1 && j == img.Height - 1)
- {
- img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, mess.Length));// записывает кол-во битов текста в последний пиксель
- break;
- }
- }
- }
- SaveFileDialog saveFile = new SaveFileDialog();
- saveFile.Filter = "Image Files (*.png, *.jpg) | *.png; *.jpg";
- saveFile.InitialDirectory = @"C:\\Users\Desktop";
- if (saveFile.ShowDialog() == DialogResult.OK)
- {
- textBoxFilePath.Text = saveFile.FileName.ToString();
- pictureBox1.ImageLocation = textBoxFilePath.Text;
- img.Save(textBoxFilePath.Text);
- }// сохранение
- }
- private void button2_Click(object sender, EventArgs e) //кнопка декодирования
- {
- Bitmap img = new Bitmap(textBoxFilePath.Text);
- string b_message = ""; //битовое сообщение
- string message = ""; //сообщение, которое должно получиться
- int m = 0; //счетчик
- Color lastpixel = img.GetPixel(img.Width - 1, img.Height - 1);
- int msgLength = lastpixel.B; // конец сообщения из битов
- for (int i = 0; i < img.Width; i++)
- {
- for (int j = 0; j < img.Height; j++)
- {
- Color pixel = img.GetPixel(i, j);
- if (m < msgLength)
- {
- int value = pixel.B;
- Console.WriteLine("Pixel.b = " + pixel.B + " bit= " + decode(value));
- b_message += decode(value);
- m++;
- }// переписывает в b_message биты первых пикселей
- }
- }
- string a = "";
- message += Convert.ToString(b_message);
- Console.WriteLine(a);
- textBoxMessage.Text = a;
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- BackColor = Color.BlueViolet;
- textBoxFilePath.BackColor = Color.Aqua;
- }
- static int code(int number,string bit) // кодирование пикселя
- {
- if ((number % 2 == 0 && bit == "1") || (number % 2 != 0 && bit == "0"))
- {
- if (number != 0)
- {
- number--;
- return number;
- }
- else number++;
- return number;
- }
- else return number;
- }
- static int decode(int number) // получение бита из пикселя
- {
- if (number % 2 == 0)
- return 0;
- else return 1;
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д