Перевод из двоичного кода в текст - C#

Узнай цену своей работы

Формулировка задачи:

Добрый день, в c# совсем новичок, занимаюсь стеганографией. Почти все сделал только немного не понимаю как раскодировать. Сначала я заливаю картинку, затем пишу сообщение. Это сообщение перевожу в двоичный код. Посредством измены последнего пикселя я меняю последний бит пиксиля на тот, который у меня в сообщении. Делаю с [0,0] пикселя и до последнего, посредством i++ и j++ в циклах. В дешифровке забираю свое сообщение в двоичном коде, которое в string'е. и что делать дальше не знаю. К примеру, string s = "10101010101010101101001010101010", прошу помочь, буду очень благодарен.

Решение задачи: «Перевод из двоичного кода в текст»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. namespace New_Steg
  12. {
  13.    
  14.     public partial class Form1 : Form
  15.     {
  16.        
  17.         public Form1()
  18.         {
  19.             InitializeComponent();
  20.         }
  21.  
  22.         private void button3_Click(object sender, EventArgs e)
  23.         {
  24.             OpenFileDialog openDialog = new OpenFileDialog();
  25.             openDialog.Filter = "Image Files (*.png, *.jpg) | *.png; *.jpg";
  26.             openDialog.InitialDirectory = @"C:\\Users\Desktop";
  27.  
  28.             if (openDialog.ShowDialog() == DialogResult.OK)
  29.             {
  30.                 textBoxFilePath.Text = openDialog.FileName.ToString();
  31.                 pictureBox1.ImageLocation = textBoxFilePath.Text;
  32.             }
  33.         }
  34.  
  35.         private void button1_Click(object sender, EventArgs e) // кнопка кодирования
  36.         {
  37.            
  38.             Bitmap img = new Bitmap(textBoxFilePath.Text);
  39.             int m = 0;  //счетчик
  40.             string mess = "";
  41.            
  42.             for (int i=0;i<textBoxMessage.TextLength;i++)
  43.             {
  44.                 char letter = Convert.ToChar(textBoxMessage.Text.Substring(i, 1));
  45.                 byte b_letter = Convert.ToByte(letter);
  46.                 mess += Convert.ToString(b_letter, 2);
  47.             }   //конвертация текста в двоичный код
  48.             Console.WriteLine("all letters " + mess);
  49.  
  50.             for (int i = 0; i < img.Width; i++)
  51.             {
  52.  
  53.                 for (int j = 0; j < img.Height; j++)
  54.                 {
  55.  
  56.                     Color pixel = img.GetPixel(i, j);
  57.                   byte b_pixel = Convert.ToByte(pixel.B); // получение кода синего пикселя
  58.                    
  59.                    
  60.                     if (m <mess.Length)
  61.                     {
  62.                        
  63.                         img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, code(b_pixel,mess.Substring(m,1))));
  64.                         Console.WriteLine("i " + i + " j " + j+ " bytes: "+ b_pixel+" mess_1 "+mess.Substring(m, 1));
  65.                         m++;
  66.                     } // изменяет голубой бит пикселя
  67.                    
  68.  
  69.                     if (i == img.Width - 1 && j == img.Height - 1)
  70.                     {
  71.                         img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, mess.Length));// записывает кол-во битов текста в последний пиксель
  72.                         break;
  73.                     }
  74.                    
  75.  
  76.                 }
  77.                
  78.             }
  79.                          
  80.             SaveFileDialog saveFile = new SaveFileDialog();
  81.             saveFile.Filter = "Image Files (*.png, *.jpg) | *.png; *.jpg";
  82.             saveFile.InitialDirectory = @"C:\\Users\Desktop";
  83.             if (saveFile.ShowDialog() == DialogResult.OK)
  84.             {
  85.                 textBoxFilePath.Text = saveFile.FileName.ToString();
  86.                 pictureBox1.ImageLocation = textBoxFilePath.Text;
  87.                 img.Save(textBoxFilePath.Text);
  88.             }// сохранение
  89.         }
  90.  
  91.         private void button2_Click(object sender, EventArgs e) //кнопка декодирования
  92.         {
  93.             Bitmap img = new Bitmap(textBoxFilePath.Text);
  94.             string b_message = "";  //битовое сообщение
  95.             string message = "";    //сообщение, которое должно получиться
  96.             int m = 0;  //счетчик
  97.            
  98.             Color lastpixel = img.GetPixel(img.Width - 1, img.Height - 1);
  99.             int msgLength = lastpixel.B; // конец сообщения из битов
  100.             for (int i = 0; i < img.Width; i++)
  101.             {
  102.  
  103.                 for (int j = 0; j < img.Height; j++)
  104.                 {
  105.                     Color pixel = img.GetPixel(i, j);
  106.                     if (m < msgLength)
  107.                     {
  108.                         int value = pixel.B;
  109.                         Console.WriteLine("Pixel.b = " + pixel.B + " bit= " + decode(value));
  110.                         b_message += decode(value);
  111.                      
  112.                         m++;
  113.  
  114.                     }// переписывает в b_message биты первых пикселей
  115.  
  116.                 }
  117.  
  118.             }
  119.  
  120.  
  121.             string a = "";
  122.  
  123.             message += Convert.ToString(b_message);
  124.            
  125.             Console.WriteLine(a);
  126.             textBoxMessage.Text = a;
  127.            
  128.         }
  129.  
  130.         private void Form1_Load(object sender, EventArgs e)
  131.         {
  132.             BackColor = Color.BlueViolet;
  133.             textBoxFilePath.BackColor = Color.Aqua;
  134.         }
  135.  
  136.        static int code(int number,string bit) // кодирование пикселя
  137.         {
  138.             if ((number % 2 == 0 && bit == "1") || (number % 2 != 0 && bit == "0"))
  139.             {
  140.                 if (number != 0)
  141.                 {
  142.                     number--;
  143.                     return number;
  144.                 }
  145.                 else number++;
  146.                 return number;
  147.             }
  148.             else return number;
  149.            
  150.         }
  151.  
  152.         static int decode(int number) // получение бита из пикселя
  153.         {
  154.             if (number % 2 == 0)
  155.                 return 0;
  156.             else return 1;
  157.         }
  158.     }
  159. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

11   голосов , оценка 4.273 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы