FFmpeg从图片生成视频:零长度图片文件导致视频中断的高效解决方案问询
Great question! Running into zero-byte files breaking your FFmpeg glob pattern is a super common headache when working with camera-captured images, and you’re right—there are cleaner, more efficient ways than checking each file individually. Here are a couple of solid approaches:
1. Use find to Generate a Filtered File List (Recommended)
The find command lets you directly filter out zero-byte files and generate a list FFmpeg can use via its concat demuxer. This is efficient, handles filenames with spaces (a future-proof habit), and avoids manual loops.
First, generate a list of valid (non-zero-byte) JPEGs:
# Create a list file formatted for FFmpeg's concat demuxer find "$ipath" -maxdepth 1 -type f -name '*.jpg' -size +0c -exec echo "file '{}'" \; > valid_images.txt
-maxdepth 1: Only search the target directory (not subfolders)-size +0c: Keep only files larger than 0 bytes-exec echo "file '{}'" \;: Format each file path to match FFmpeg's concat requirements
Then update your FFmpeg command to use this list instead of the glob pattern:
/usr/bin/ffmpeg -loglevel info -framerate 4 \ -f concat -safe 0 -i valid_images.txt \ -c:v libx264 -crf 30 -y -pix_fmt yuv420p "$temp" &>> "$log"
-f concat: Tell FFmpeg to use the concat demuxer-safe 0: Allow absolute file paths in the list
After running, clean up the temporary list file with rm valid_images.txt.
2. Use a Shell Array to Filter Files
If you prefer avoiding intermediate files, collect valid images into a shell array first. This is straightforward and works well for moderate numbers of files:
# Initialize an empty array for valid images valid_images=() # Loop through all JPEGs and add non-zero-byte ones to the array for img in "$ipath"/*.jpg; do if [[ -s "$img" ]]; then # -s checks if the file has non-zero size valid_images+=("$img") fi done # Only run FFmpeg if there are valid images to process if [[ ${#valid_images[@]} -gt 0 ]]; then /usr/bin/ffmpeg -loglevel info -framerate 4 \ -i "${valid_images[@]}" \ -c:v libx264 -crf 30 -y -pix_fmt yuv420p "$temp" &>> "$log" fi
Why These Work Better Than Manual Checks
Both methods avoid the overhead of slow, manual per-file checks. The find approach is optimized for large file sets and handles edge cases like filenames with special characters, while the shell array method keeps everything self-contained without temporary files. Either way, FFmpeg will only process valid images, preventing the early termination you encountered.
内容的提问来源于stack exchange,提问作者Buadhai

