Use FFmpeg, a powerful multimedia processing tool, to easily convert a series of images into an MP4 video file. Here is a basic command line example to accomplish this task:
ffmpeg -framerate 25 -i image-% -c:v libx264 -r 30 -pix_fmt yuv420p output.mp4
Command parameter description:
-framerate 25: Set the frame rate of the input image sequence, which indicates 25 frames per second.
-i image-%: Specifies the input file format, where %03d is a placeholder that represents the index of three digits (for example:, , ...). FFmpeg will find and read the pictures in order in this pattern.
-c:v libx264: Specifies that the output video stream is compressed using the H.264 encoder (libx264).
-r 30: Set the frame rate of the output video, here is 30 frames per second.
-pix_fmt yuv420p: Specifies that the color pixel format of the output video is YUV 4:2:0 Planar, which is a widely compatible format.
output.mp4: The final output MP4 video file name.
If the image file name is not represented in a specific sequence of numbers, you need to adjust the file name template after the -i parameter according to the actual situation. At the same time, frame rate and other parameters should also be adjusted according to actual needs. If the source image and target video have special resolution requirements, additional parameters such as -s WIDTHxHEIGHT can be added to specify the resolution.
Use C# to call the FFmpeg command line to convert the image sequence to MP4 video. Here is a simple example:
using ; public class FfmpegWrapper { /// <summary> /// Execute FFmpeg /// </summary> /// <param name="inputPattern">Input file name mode</param> /// <param name="outputVideoPath">Output file path</param> /// <param name="frameRate">Frame rate</param> public static void ConvertImagesToMp4(string inputPattern, string outputVideoPath, int frameRateInput = 25, int frameRateOutput = 30) { // Build the FFmpeg command line string string command = $"ffmpeg -framerate {frameRateInput} -i \"{inputPattern}\" -c:v libx264 -r {frameRateOutput} -pix_fmt yuv420p \"{outputVideoPath}\""; // Create process object Process process = new Process(); // Set startup information ProcessStartInfo startInfo = new ProcessStartInfo("ffmpeg") { Arguments = command, UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true }; // Assign startup information to process objects = startInfo; // Start the FFmpeg process (); // If necessary, you can obtain the error output or standard output in the following way // string errorOutput = (); // string standardOutput = (); // Wait for the process to end (); // Check the exit code to confirm whether it is successful int exitCode = ; if (exitCode != 0) { throw new Exception($"FFmpeg exited with code {exitCode}"); } } } //Usage example:FfmpegWrapper.ConvertImagesToMp4("image-%", "output.mp4");
Note that the above code assumes that the FFmpeg executable already exists in the system's PATH environment variable, otherwise you need to provide the FFmpeg full path to it.
In addition, if your application scenario is complex or requires deeper control, you can consider using a .NET binding library such as this to directly call FFmpeg's API for programming, rather than through the command line interface. However, this usually involves more underlying operations and understanding of how FFmpeg works internally.
%03d represents a three-digit index
In some programming contexts, %03d is a placeholder expression for formatting strings, which is commonly found in printf-style string formatting functions in programming languages such as C, C++, Java, and Python. %03d here means formatting an integer into a decimal number that occupies at least three digits of width. If less than three digits are less than three, zero will be added to the left to achieve a fixed width.
- %d represents an integer;
- 0 means that the padding character is zero;
- 3 means the minimum width is 3.
So, if you need a four- or five-digit numeric index, the corresponding expression will be:
- Four-digit number index: %04d, for example, the number 1 will be formatted as "0001";
- Five-digit number index: %05d, for example, the number 1 will be formatted as "00001".
The purpose of this is usually to ensure that the output numbers have a fixed length, which is easy to align or other forms of unified processing.
In a Windows environment, assuming that the FFmpeg executable file is located in the system PATH environment variable, the above command can be run directly in the command prompt window. If not, you need to specify the FFmpeg full path, for example:
"C:\path\to\" -framerate 25 -i image-% -c:v libx264 -vf format=yuv420p -crf 23 -pix_fmt yuv420p output.mp4
If it is not in the system environment variable PATH and cannot be called directly through the command line, it needs to provide its full path. In this case, the FileName property should be set to the full path, for example:
string ffmpegFullPath = @"C:\Program Files\FFmpeg\bin\"; = ffmpegFullPath;
The inputPattern parameter can contain path information. In the command line parameter of FFmpeg, it can be a full or relative path to the image file. For example, if your image is located in a directory, you can set the inputPattern like this:
string imagesFolderPath = @"C:\MyImages"; string inputPattern = $"{imagesFolderPath}\\image-%"; (inputPattern, "output.mp4", 25);
-c:v libx264 Specifies that FFmpeg uses the H.264 video encoder, which is a very common video encoding format because of its efficient compression performance and extensive device support. In addition to libx264, FFmpeg supports a variety of other video encoders, such as:
- libopenh264: OpenH264 encoder
- libvpx-vp9: VP9 encoder
- libaom-av1: AV1 encoder
- mpeg4 or libxvid: MPEG-4 Part 2 Encoder
- mpeg2video or libmpeg2: MPEG-2 encoder
- libtheora: Theora encoder
- vp8 or libvpx: VP8 encoder
- hevc or libx265: H.265/HEVC encoder
For the -pix_fmt parameter, it is the pixel format (Pixel Format) that specifies the output video. yuv420p is a common pixel format, especially for the H.264 encoder, which is a very compatible YUV 4:2:0 Planar format. However, FFmpeg supports a variety of different pixel formats, such as:
- yuv422p
- yuv444p
- nv12
- p010le (10-bit depth YUV 4:2:0 format)
- rgb24
- rgba
- gray (Grayscale)
Which pixel format you choose depends on your specific needs, including encoding efficiency, color accuracy, hardware acceleration support and other factors. For example, if you need higher color fidelity, you might choose the yuv444p or rgb format; while for most video streaming and storage applications, yuv420p is more common due to its lower data volume.
Note:
Make sure that the width of the input image is even, you can make it even by adjusting the image size or adding a filter.
Check FFmpeg command line parameters, especially encoding-related options such as bit rate, frame rate, resolution, etc. to make sure they are compatible with the target encoder.
If needed, try updating the FFmpeg version or reconfiguring the codec parameters to suit specific needs.
The above is the detailed content of C# using ffmpeg to save pictures as mp4 videos. For more information about saving C# ffmpeg pictures as mp4, please pay attention to my other related articles!