65.9K
CodeProject 正在变化。 阅读更多。
Home

在图像中保存文本数据

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (13投票s)

2014年10月24日

MIT

1分钟阅读

viewsIcon

17600

downloadIcon

666

以图像格式保存文本数据

文本保存方式如下:

引言

我尝试编写一个新的字符串压缩器,但相信我,这并不容易。我尝试将文本保存到图像的RGB中,并将其移动到灰度,但我发现这不可行,或者会占用更多的字节。无论如何,我将此代码发送给您,也许可以节省您的时间。

  1. LoadText(点击“com”):您可以在图像中看到您的文本,就像顶部图像一样。
  2. SaveImage:点击图像,保存它。
  3. LaodImage(点击“decom”):您可以保存保存在图像中的文本。

MainClass

您可以使用 com 和 decom 类。

                com nbv = new com();
                nbv.doCompress(String, String);

Decom图像类

                decom nb = new decom();
                nb.doDeCompress(String,String);

 

背景

 

使用代码

此类将int字放入RGB(X1,X2,X3)中,其值小于255。获取表示图像大小的总字母数的平方根,该值除以三,因为每个像素包含3个字母。

引用
将字符转换为ASCII值并添加到letters集合中
混合像素中的RGB(R,G,b)
   class com
    {
        public void doCompress(string FileText, string FileImage)
        {

            using (StreamReader sr = File.OpenText(FileText)) 
            // Get text from a .txt file to compress
            {

                var line = ""; // To hold a line of the file
                var R = 0; // To hold 4 letters as Red value
                var G = 0; // To hold 4 letters as Green value
                var B = 0; // To hold 4 letters as Blue value
                var letters = new List(); 
                // To hold the characters of line
                //Read lines one by one from stream reader
                while ((line = sr.ReadLine()) != null)

                {
                    foreach (char ch in line) // Get character from a line
                    {
                        letters.Add(Convert.ToInt16(ch)); 
                        // Convert the character
                        //into ASCII value and add in letters collection
                    }

                    letters.Add(255); // Use 255 as a flag that indicates new line
                    //counter_line++;
                }

               /* Get square root of total letter that indicate size 
                of the image (get the value divided by three since each 
                pixel contains 3 letters*/
                var square = Math.Sqrt(letters.Count / 3);
                /* Get square root of total letter that indicate size 
                 * of the image (get the value divided by three since
                 * each pixel contains 3 letters*/
                square += 1; // Add one value for any exceeds if any
                square = Math.Round(square);
                // Have a BitMap with optimal size that we calculated
                var bmp = new Bitmap((int)square, (int)square);
                var count = 0; // count for letters

                for (int row = 1; row < square; row++) // Indicates row number
                {
                    for (int column = 1; column < square; column++) // Indicate column number
                    {
                        if (count < (letters.Count - 3)) // Check for last pixel
                        {
                            R = letters[count++]; // Assignee a letter in Red value
                            G = letters[count++]; // Assignee a letter in Green value
                            B = letters[count++]; // Assignee a letter in Blue value
                            // Set pixel with the combination of two value
                            bmp.SetPixel(row, column, (Color.FromArgb( R, G, B))); 
                        }
                    }
                }
              
            
                    bmp.Save(FileImage, ImageFormat.Png); //Save the Bitmap and this is the compressed Image Data
         
             
            }
        }

    }

此类获取RGB颜色列表并转换字符

  1. 获取红色->转换字符
  2. 获取绿色->转换字符
  3. 获取蓝色->转换字符
   class decom
    {
        public void doDeCompress(string FileImage,string FileText)
        {

            var lettersExtract = new List(); // To hold extracted letters

            var bmp = new Bitmap(Bitmap.FromFile(FileImage)); 
            // Get the Image data to DeCompress

            for (int row = 1; row < bmp.Width; row++) // Indicates row number
            {

                for (int column = 1; column < bmp.Height; column++) 
               // Indicate column number
                {

                    var cr = bmp.GetPixel(row, column); 
                   // Get the pixel of the current row and column

                    lettersExtract.Add(cr.R); 
                   // Get the Red Value and Add in letterExtract collection

                    lettersExtract.Add(cr.G); 
                   // Get the Green Value and Add in letterExtract collection

                    lettersExtract.Add(cr.B); 
                   // Get the Blue Value and Add in letterExtract collection

                }

            }

            using (System.IO.StreamWriter file = new 
            System.IO.StreamWriter(FileText,false,Encoding.Default)) 
                 // Open a text file to extract
            {

                foreach (int write in lettersExtract)
              //Get color value one by one from the letters Extracted
                {
                    if (write == 255) 
              //Condition check for new line since 255 is a flag of new line
                        file.WriteLine("");
                    else
                        file.Write((Char)write); 
              // Write the character in the file by converting 
              //  the color value into   character

                }

            }

        }
    }

在GUI Windows中混合所有数据:

我使用 openFileDialog 和 saveFileDialog。

  • 将文本加载到 RichTextBoxStream 中
  • 将临时图像加载到 PictureBox 中(PictureBoxSizeMode.StretchImage)
  • 点击图像并保存它(AppDomain.CurrentDomain.BaseDirectory ,pictureBox.Image.Save(URL))。
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        static string word;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string Chosen_File = "";
            string name_image_save = AppDomain.CurrentDomain.BaseDirectory.ToString() 
             + "\\" + "compressed.png";  // temp file
            openFileDialog1.InitialDirectory = Application.ExecutablePath.ToString();
            openFileDialog1.Title = "Load text";
            openFileDialog1.Filter = "Text Normal|*.txt|Text INF|*.inf";
            if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
            {
                //richTextBox1
                Chosen_File = openFileDialog1.FileName;
                richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
                //-------------- use class 
                com nbv = new com();
                nbv.doCompress(Chosen_File, name_image_save);
                //------------
            }
            pictureBox1.Load(name_image_save);
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

        }

        private void button2_Click(object sender, EventArgs e)
        {

            string Chosen_File = "";
            string name_text_save = AppDomain.CurrentDomain.BaseDirectory.ToString()
             + "\\" + "decompress.txt";
            openFileDialog2.InitialDirectory = Application.ExecutablePath.ToString();
            openFileDialog2.Title = "Load image";
            openFileDialog2.Filter = "Image Normal|*.PNG";
            if (openFileDialog2.ShowDialog() != DialogResult.Cancel)
            {
                //richTextBox1
                Chosen_File = openFileDialog2.FileName;
                pictureBox2.Load(Chosen_File);
                //-------------------
                decom nb = new decom();
                nb.doDeCompress(Chosen_File, name_text_save);
                //--------------------
                pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
                richTextBox2.LoadFile(name_text_save, RichTextBoxStreamType.PlainText);
            }
               
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            try // control error
            {
                string Chosen_File = "";
                string name_image_save = AppDomain.CurrentDomain.BaseDirectory.ToString() 
                + "\\" + "compressed.png";
                saveFileDialog1.InitialDirectory = Application.ExecutablePath.ToString();
                saveFileDialog1.Title = "Save Image";
                saveFileDialog1.Filter = "Image Normal|*.PNG";
                if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
                {
                    //richTextBox1
                    Chosen_File = saveFileDialog1.FileName;

                    pictureBox1.Image.Save(Chosen_File);
                    MessageBox.Show("Image Save it");

                }
            }
            catch
            {
                MessageBox.Show("not find any image in pictureBox1");
            }
        }

    }
}
© . All rights reserved.