欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#图像转字符串

程序员文章站 2022-03-25 10:35:10
...

生成方法

 class ImageConvert
 {
 		private static readonly string brightStr = "MNHQ&OC?7>!:-;. ";
		/// <summary>
        ///  图像转string
        /// </summary>
        /// <param name="bitmap">图片</param>
        /// <param name="zoomWidth">宽度缩放0.1-1</param>
        /// <param name="zoomHeight">高度缩放0.1-1</param>
        /// <returns></returns>
        public static string Generate(Bitmap bitmap, double zoomWidth,double zoomHeight)
        {
            StringBuilder result = new StringBuilder();
            int bitmapH = bitmap.Height;
            int bitmapW = bitmap.Width;


            int outH = Convert.ToInt32(bitmapH * zoomHeight);
            int outW = Convert.ToInt32(bitmapW * zoomWidth);
            int areaCountH = bitmapH / outH;
            int areaCountW = bitmapW / outW;

            for (int h = 0; h < outH; h++)
            {
                for (int w = 0; w < outW; w++)
                {
                    double averBright = 0;
                    int sY = (int)(h / zoomHeight);
                    int sX = (int)(w / zoomWidth);
                    for (int y = sY; y < sY + areaCountH; y++)
                    {
                        for (int x = sX; x < sX + areaCountW; x++)
                        {
                            Color color = bitmap.GetPixel(x, y);
                            averBright += color.GetBrightness();//获取亮度
                        }
                    }
                    averBright /= (areaCountH * areaCountW);
                    int index = (int)(averBright / (1.0 / brightStr.Length));
                    if (index >= brightStr.Length)
                    {
                        result.Append(brightStr[brightStr.Length - 1]);
                    }
                    else
                    {
                        result.Append(brightStr[index]);
                    }
                }
                result.Append("\r\n");
            }
            return result.ToString();
        }

调用

private void ImageSelect_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog()
    {
        Filter = "图片|*.jpg;*.png;",
        Multiselect = false
    };
    if (openFileDialog.ShowDialog() == true)
    {
        string path = openFileDialog.FileName;
        Bitmap bitmap = new Bitmap(path);
        string savePath = $"{Environment.CurrentDirectory}\\{Guid.NewGuid()}.txt";
        string result = ImageConvert.Generate(bitmap,1,1);
        File.WriteAllText(savePath, result);
    }
}


效果

C#图像转字符串

相关标签: C# c#