C#实现图片转字符画

原理:彩图-->灰度图-->字符画

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;

namespace image2char
{
    class Program
    {
        private static string imgPath = @"D:\个人\图片\聪聪.jpg";
        private static string urlG = @"D:\个人\字符画\g.jpg";
        private static string TxtPath = @"D:\个人\字符画\Txt.txt";
        private static string app_dir = System.AppDomain.CurrentDomain.BaseDirectory;//当前运行进程的根目录  
 
        protected static readonly string charset = "MNHQ&OC?7>!:-;. ";
        static void Main(string[] args)
        {
            Program p = new Program();
            p.img2char();

        }

        //灰度图转字符画
        private void img2char()
        {
            try
            {
                Program p = new Program();
                char[] CharArr = charset.ToArray<char>();

                string Write2Txt = "";
                Bitmap bim = p.ToG();//灰度图

                for (int i = 0; i < bim.Height; i += 4)
                {
                    for (int j = 0; j < bim.Width; j+=2)
                    {
                        Color origalColor = bim.GetPixel(j, i);
                        int index = (int)((origalColor.R + origalColor.G + origalColor.B) / 768.0 * CharArr.Length);
                        Write2Txt += CharArr[index];
                    }
                    Write2Txt += "\r\n";
                }
                
                StreamWriter writer = new StreamWriter(TxtPath, false);
                writer.Write(Write2Txt);
                writer.Close();
                writer.Dispose();
            }
            catch (Exception e)
            {
                Console.Write("程序执行出现错误:"+e.ToString());
                Console.ReadKey();
            }
        }

        //将彩图转成灰度图
        private Bitmap ToG()
        {
            if (File.Exists(urlG))
                File.Delete(urlG);
            Bitmap bim = new Bitmap(imgPath);
            Bitmap bimG = new Bitmap(bim.Width, bim.Height);

            for (int i = 0; i < bim.Width; i++)
            {
                for (int j = 0; j < bim.Height; j++)
                {
                    Color c = bim.GetPixel(i, j);
                    int rgb = (int)(c.R * 0.299 + c.G * 0.587 + c.B * 0.114);
                    bimG.SetPixel(i, j, Color.FromArgb(rgb, rgb, rgb));
                }
            }
            bimG.Save(urlG);
            return bimG;
        }

    }
}

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值