基于C#实现乱码视频效果
Csharp小记 人气:0文章描述
这个效果可能很多人都在抖音看到过,即把一个短视频,转成数字、字母等乱码组成的形式进行播放。
开发环境
.NET Framework版本:4.5
开发工具
Visual Studio 2013
实现代码
private void btn_convert_Click(object sender, EventArgs e) { string framePath = Application.StartupPath + "\\temp"; if (Directory.Exists(framePath)) { Directory.Delete(framePath, true); } Directory.CreateDirectory(framePath); //string newFramePath = Application.StartupPath + "\\newTemp"; //if (Directory.Exists(newFramePath)) //{ // Directory.Delete(newFramePath, true); //} //Directory.CreateDirectory(newFramePath); FFmpegUtil.Split(axWindowsMediaPlayer1.URL, framePath); List<char> listChar = new List<char>(); for (char i = 'a'; i <= 'z'; i++) { listChar.Add(i); } for (char i = 'A'; i <= 'Z'; i++) { listChar.Add(i); } for (char i = '0'; i <= '9'; i++) { listChar.Add(i); } string[] imgUrls = Directory.GetFiles(framePath); Bitmap img = null; for (int u = 0; u < imgUrls.Length; u++) { img = (Bitmap)Image.FromFile(imgUrls[u]); double threshold = ImageUtil.GetAverageThreshold(img); ImageUtil.Threshold(img, threshold); StringBuilder builder = new StringBuilder(); Random random = new Random(); for (int y = 0; y < img.Height; y += 16) { for (int x = 0; x < img.Width; x += 8) { if (ImageUtil.GetGrayValue(img.GetPixel(x, y)) < threshold) { builder.Append(listChar[random.Next(62)]); } else { builder.Append(" "); } } builder.Append("\r\n"); } File.WriteAllText(@"C:\Users\Zero\Desktop\a\b\" + u + ".txt", builder.ToString()); } MessageBox.Show("转换完成"); } private void btn_show_Click(object sender, EventArgs e) { new FormShow(@"C:\Users\Zero\Desktop\a\b\").Show(); }
private void FormShow_Load(object sender, EventArgs e) { List<string> list = Directory.GetFiles(_path, "*.txt").ToList(); if (list.Count == 0) { return; } list.Sort((a, b) => { string reg = "[0-9]+"; int a_index = int.Parse(Regex.Match(a, reg).Value); int b_index = int.Parse(Regex.Match(b, reg).Value); return a_index.CompareTo(b_index); }); richTextBox1.Text = File.ReadAllText(list[0]); Width = richTextBox1.Lines.Max(s => s).Length * 5; Height = richTextBox1.Lines.Length * 10; Location = new Point(Location.X, 10); new Task(async () => { foreach (string str in list) { if (!this.IsDisposed) { this.BeginInvoke(new Action(() => { richTextBox1.Text = File.ReadAllText(str); })); } await Task.Delay(260); } }).Start(); }
实现效果
代码解析:实现原理是首先利用ffmpeg将视频分割成一帧帧的图片,然后将每张图片进行一个二值化处理,最后判断灰度值,大于阈值的情况下随便输入一个字符,否则就输入空格。这里是使用了字符串来记录了各个图片的生成情况,最后保存到一个个的记事本中去。
在展示页面中,只需要将文件夹中的记事本文档按照顺序排列并逐个读取显示即可。
加载全部内容