Display a Image in a console application

后端 未结 7 1993
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 10:06

I have a console application that manages images. Now i need something like a preview of the Images within the console application. Is there a way to display them in the con

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 10:19

    If you use ASCII 219 ( █ ) twice, you have something like a pixel ( ██ ). Now you are restricted by the amount of pixels and the number of colors in your console application.

    • if you keep default settings you have about 39x39 pixel, if you want more you can resize your console with Console.WindowHeight = resSize.Height + 1;and Console.WindowWidth = resultSize.Width * 2;

    • you have to keep the image's aspect-ratio as far as possible, so you won't have 39x39 in the most cases

    • Malwyn posted a totally underrated method to convert System.Drawing.Color to System.ConsoleColor

    so my approach would be

    using System.Drawing;
    
    public static int ToConsoleColor(System.Drawing.Color c)
    {
        int index = (c.R > 128 | c.G > 128 | c.B > 128) ? 8 : 0;
        index |= (c.R > 64) ? 4 : 0;
        index |= (c.G > 64) ? 2 : 0;
        index |= (c.B > 64) ? 1 : 0;
        return index;
    }
    
    public static void ConsoleWriteImage(Bitmap src)
    {
        int min = 39;
        decimal pct = Math.Min(decimal.Divide(min, src.Width), decimal.Divide(min, src.Height));
        Size res = new Size((int)(src.Width * pct), (int)(src.Height * pct));
        Bitmap bmpMin = new Bitmap(src, res);
        for (int i = 0; i < res.Height; i++)
        {
            for (int j = 0; j < res.Width; j++)
            {
                Console.ForegroundColor = (ConsoleColor)ToConsoleColor(bmpMin.GetPixel(j, i));
                Console.Write("██");
            }
            System.Console.WriteLine();
        }
    }
    

    so you can

    ConsoleWriteImage(new Bitmap(@"C:\image.gif"));
    

    sample input:

    sample output:

提交回复
热议问题