yangbin1005
原理:

一张m*n大小的图片,实际上可以看成是一个m*n的矩阵。矩阵的每一个元素就是一个Color值,不同的Color值,用不同的Ascii可以在屏幕上打印显示的字符来代替,于是可以得到一个m*n的每一个元素是一个Ascii字符的两维矩阵,矩阵的每一行就是像素矩阵的每一行。再把这个字符矩阵输出到文本文件中保存,便可以得到图像对应的文本文件。

当然了,所用的Ascii字符越多,生成的图像也就越逼真。如果只用两个字符,就相当于生成了只有黑白两色的黑白照片一样。
代码:
if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
            
{
                
return;
            }

            StringBuilder sb 
= new StringBuilder();
            
char[] asciiChars = new char[255];//{\'@\',\'#\',\'.\',\'$\',\'%\',\'^\',\'&\',\')\',\'(\',\'*\',\'.\',\'_\',\'=\',\'-\',\'=\',\'*\',\'/\',\',\',\'!\',\'?\',\'<\',\'>\',\';\',\'"\'};
            for (int i = 0; i < 200; i++)
            
{
                
char c = (char)i;
                
if (c == \'\0\' || c == \'\n\' || c == \'\r\' || c == \'\t\')
                
{
                    c 
= \'.\';
                }

                asciiChars[i] 
= c;
            }

            
char[] asciiChars = new char[] \'.\'\'*\' };
            Image img 
= Image.FromFile(openFileDialog1.FileName);
            Bitmap image 
= new Bitmap(img);
            
for (int h = 0; h < image.Height; h++)
            
{
                
for (int w = 0; w < image.Width; w++)
                
{
                    Color pixelColor 
= image.GetPixel(w, h);
                    
//用均值法算出灰度值
                    int red = (pixelColor.R + pixelColor.G + pixelColor.B) / 3;
                    
int green = (pixelColor.R + pixelColor.G + pixelColor.B) / 3;
                    
int blue = (pixelColor.R + pixelColor.G + pixelColor.B) / 3;

                    Color grayColor 
= Color.FromArgb(red, green, blue);
                    
int index = (grayColor.R * 10/ 255 ;//% 2;
                    char a = asciiChars[index];
                    sb.Append(asciiChars[index]);    
//char[] asciiChars 为存储字符的数组。
                }


                sb.Append(
"\r\n");   //一行结束,加一个回车换行
            }

            
this.textBox1.Text = sb.ToString();

http://www.chenjiliang.com/Article/View.aspx?ArticleID=12568&TypeID=79

分类:

技术点:

相关文章:

  • 2022-01-04
  • 2021-12-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-20
  • 2021-11-18
猜你喜欢
  • 2021-09-01
  • 2021-12-24
  • 2021-08-05
  • 2022-12-23
  • 2021-09-26
相关资源
相似解决方案