目的:实现在winfrom中,用代码实现截屏mp4视频,生成以时间为后缀的图片。
界面图如下:
界面图
截屏成功后,提示图
在代码操作前,先如下图操作:
操作图
1、将ffmpeg.exe这个控件放到根目录下,一般为WindowsFormsApplication名字\bin\Debug\ 下
2、此为截屏后生成的照片,暂不管(也可以代码自己修改保存路径)
3、此为需要被截屏的视频存放位置(也可以代码自己修改,视频读取路径)
下面为代码实现的操作:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
readPic();
}
string cutTime = "";
string PicPath0 = string.Format("{0}jietu.jpg", AppDomain.CurrentDomain.BaseDirectory);
private void button1_Click(object sender, EventArgs e)
{
string name = string.Format("{0}测试.mp4", AppDomain.CurrentDomain.BaseDirectory);
double time = axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
cutTime = time.ToString();
if (time < 100 && time >= 10)
{
cutTime = string.Format("0{0}",time);
}
else if (time < 10)
{
cutTime = string.Format("00{0}", time);
}
string cutImagePath = GetPicFromVideo(name, cutTime);
if (File.Exists(cutImagePath))
{
MessageBox.Show(@"图片截取成功!");
}
else
{
MessageBox.Show(@"图片截取失败!");
}
}
private void readPic()
{
string a = string.Format("{0}测试.mp4", AppDomain.CurrentDomain.BaseDirectory);
axWindowsMediaPlayer1.URL = a;
axWindowsMediaPlayer1.uiMode = "Full";
int playState = (int)axWindowsMediaPlayer1.playState;
}
public string videoPath = string.Format("{0}测试.mp4", AppDomain.CurrentDomain.BaseDirectory);
public string GetPicFromVideo(string VideoName, string CutTimeFrame)
{
videoPath = get_uft8(videoPath);
string ffmpeg = string.Format("{0}ffmpeg.exe", AppDomain.CurrentDomain.BaseDirectory);
string saveImgPath = System.IO.Path.ChangeExtension(PicPath0, "-" cutTime.Replace(":", ":") ".jpg");
saveImgPath = get_uft8(saveImgPath);
string saveImgSize = "852x480";
ProcessStartInfo startInfo = new ProcessStartInfo(ffmpeg);
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.Arguments = string.Format(" -i \"{0}\" -y -f image2 -ss {1} -t 0.001 -s \"{2}\" \"{3}\"", videoPath, cutTime, saveImgSize, saveImgPath);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
System.Diagnostics.Process p = new Process();
p.StartInfo = startInfo;
p.Start();
p.WaitForExit();
return saveImgPath;
}
public string get_uft8(string unicodeString)
{
UTF8Encoding utf8 = new UTF8Encoding();
Byte[] encodedBytes = utf8.GetBytes(unicodeString);
String decodedString = utf8.GetString(encodedBytes);
return decodedString;
}
}
}
编译后,点击button就行了。
,