ffmpeg转换字符动画
1 using FFmpeg.NET; 2 using System; 3 using System.DrawingCore; 4 using System.Text; 5 using System.Threading; 6 7 namespace VideoToChar 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //Console.BackgroundColor = ConsoleColor.White; 14 //Console.ForegroundColor = ConsoleColor.Black; 15 Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight); 16 //Console.SetBufferSize(1800, 800); 17 18 19 var inputFile = new MediaFile(@"d:\ffmpeg\1.mp4"); 20 var outputFile = new MediaFile(@"d:\ffmpeg\1.jpg"); 21 22 var ffmpeg = new Engine(@"d:\ffmpeg\ffmpeg.exe"); 23 24 var fls = System.IO.Directory.GetFiles(@"d:\ffmpeg\img\"); 25 if (fls.Length < 1) 26 { 27 try 28 { 29 double ss = 0.0; 30 while (ss < 10) 31 { 32 // 保存位于视频第 s 秒的帧。 33 var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(ss) }; 34 35 var url = $@"d:\ffmpeg\img\{ss}.jpg"; 36 var img = new MediaFile(url); 37 38 ffmpeg.GetThumbnailAsync(inputFile, img, options).Wait(); 39 40 //ConvertToChar(new Bitmap(url), 3, 6); 41 42 ss += (1.0 / 24); 43 } 44 } 45 catch (Exception) 46 { 47 Console.ReadKey(); 48 } 49 } 50 51 52 foreach (var item in System.IO.Directory.GetFiles(@"d:\ffmpeg\img\")) 53 { 54 ConvertToChar(new Bitmap(item), 2, 3); 55 Thread.Sleep(1000 / 24); 56 } 57 58 Console.ReadKey(); 59 } 60 61 /// <summary> 62 /// 将图片转换为字符画 63 /// </summary> 64 /// <param name="bitmap">Bitmap类型的对象</param> 65 /// <param name="WAddNum">宽度缩小倍数(如果输入3,则以1/3倍的宽度显示)</param> 66 /// <param name="HAddNum">高度缩小倍数(如果输入3,则以1/3倍的高度显示)</param> 67 public static void ConvertToChar(Bitmap bitmap, int WAddNum, int HAddNum) 68 { 69 StringBuilder sb = new StringBuilder(); 70 string replaceChar = "@*#$%XB0H?OC7>+v=~^:_-'`. "; 71 for (int i = 0; i < bitmap.Height; i += HAddNum) 72 { 73 for (int j = 0; j < bitmap.Width; j += WAddNum) 74 { 75 //获取当前点的Color对象 76 Color c = bitmap.GetPixel(j, i); 77 //计算转化过灰度图之后的rgb值(套用已有的计算公式就行) 78 int rgb = (int)(c.R * .3 + c.G * .59 + c.B * .11); 79 //计算出replaceChar中要替换字符的index 80 //所以根据当前灰度所占总rgb的比例(rgb值最大为255,为了防止超出索引界限所以/256.0) 81 //(肯定是小于1的小数)乘以总共要替换字符的字符数,获取当前灰度程度在字符串中的复杂程度 82 int index = (int)(rgb / 256.0 * replaceChar.Length); 83 //追加进入sb 84 sb.Append(replaceChar[index]); 85 } 86 //添加换行 87 sb.Append("\r\n"); 88 } 89 Console.Clear(); 90 Console.Write(sb.ToString()); 91 } 92 93 } 94 }