码迷,mamicode.com
首页 > 其他好文 > 详细

BitmapToASCii

时间:2018-08-06 23:21:55      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:--   ict   highlight   space   exception   draw   ring   ascii   idt   

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

namespace PicToASCii
{
    public static class ASCiiHelper
    {
        public static string Generate(Bitmap bitmap, int rowSize, int colSize, int type)
        {
            StringBuilder result = new StringBuilder();
            char[] charset = { ‘ ‘, ‘.‘, ‘,‘, ‘:‘, ‘;‘, ‘i‘, ‘1‘, ‘r‘, ‘s‘, ‘5‘, ‘3‘, ‘A‘, ‘H‘, ‘9‘, ‘8‘, ‘&‘, ‘@‘, ‘#‘ };
            if (type == 1)
            {
                //charset = new char[] { ‘8‘, ‘9‘, ‘6‘, ‘4‘, ‘3‘, ‘5‘, ‘7‘, ‘0‘, ‘2‘, ‘1‘, ‘.‘,‘ ‘ };
                charset = new char[] { ‘ ‘, ‘.‘, ‘1‘, ‘2‘, ‘0‘, ‘7‘, ‘5‘, ‘3‘, ‘4‘, ‘6‘, ‘9‘, ‘8‘ };
            }
            else if (type == 2)
            {
                charset = new char[] { ‘丶‘, ‘卜‘, ‘乙‘, ‘日‘, ‘瓦‘, ‘車‘, ‘馬‘, ‘龠‘, ‘齱‘, ‘龖‘ };
            }
            int bitmapH = bitmap.Height;
            int bitmapW = bitmap.Width;
            for (int h = 0; h < bitmapH / rowSize; h++)
            {
                int offsetY = h * rowSize;
                for (int w = 0; w < bitmapW / colSize; w++)
                {
                    int offsetX = w * colSize;
                    float averBright = 0;
                    for (int j = 0; j < rowSize; j++)
                    {
                        for (int i = 0; i < colSize; i++)
                        {
                            try
                            {
                                Color color = bitmap.GetPixel(offsetX + i, offsetY + j);
                                averBright += color.GetBrightness();
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                averBright += 0;
                            }
                        }
                    }
                    averBright /= (rowSize * colSize);
                    int index = (int)(averBright * charset.Length);
                    if (index == charset.Length)
                        index--;
                    result.Append(charset[charset.Length - 1 - index]);
                }
                result.Append("\r\n");
            }
            return result.ToString();
        }
    }
}

  

BitmapToASCii

标签:--   ict   highlight   space   exception   draw   ring   ascii   idt   

原文地址:https://www.cnblogs.com/iWaitYou/p/9434014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!