FfmpegUtil.java 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package api.common.util;
  2. import lombok.SneakyThrows;
  3. import org.apache.commons.io.FileUtils;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.util.Arrays;
  7. public class FfmpegUtil {
  8. /**
  9. * @param sourcePath 原始图片路径
  10. * @param videoPath 视频生成路径
  11. * @param filename 视频文件名称
  12. * @param ffmpeg 视频软件路径
  13. */
  14. @SneakyThrows
  15. public static void imgToMp4(String sourcePath, String videoPath, String filename, double inputFrameRate, String ffmpeg) {
  16. int nameLength = copyImgToTemp(sourcePath);
  17. String execute = LinuxUtil.execute(ffmpeg
  18. + " -r " + inputFrameRate
  19. + " -i " + FileUtil.addSeparator(sourcePath) + "tmp/image%0" + nameLength + "d.tga"
  20. + " -y "
  21. + videoPath + "/" + filename + ".mp4"
  22. );
  23. }
  24. /**
  25. * 计算帧率
  26. *
  27. * @param imageNumber 图片数量
  28. * @param second 视频长度
  29. * @param decimalPlaces 帧率保留几位小数
  30. * @return 帧率
  31. */
  32. public static double computeFramerate(int imageNumber, int second, int decimalPlaces) {
  33. return Math.round(imageNumber * Math.pow(10.0, decimalPlaces) / second) / Math.pow(10.0, decimalPlaces);
  34. }
  35. private static int copyImgToTemp(String sourcePath) throws IOException {
  36. File file = new File(sourcePath);
  37. File[] files = file.listFiles();
  38. assert files != null;
  39. Arrays.sort(files);
  40. String[] names = file.list();
  41. assert names != null;
  42. Arrays.sort(names);
  43. int nameLength = getLen(names.length);//获取图片总张数的位数大小,用于补齐图片名称,例如image000.jpg,image001.jpg ....image999.jpg
  44. int makeUpMaxNum = getMakeUpMaxNum(nameLength);//图片名字需要补齐的最大数
  45. if (names.length > 0) {
  46. String tmpPath = sourcePath + "/tmp";
  47. new File(tmpPath).mkdir();
  48. for (int i = 0; i < names.length; i++) {
  49. String name = names[i];
  50. if (name.lastIndexOf(".") > 0) {
  51. int lo = name.lastIndexOf(".");
  52. String lastName = name.substring(lo);
  53. String forNeName = String.valueOf(i);
  54. if (i <= makeUpMaxNum) {
  55. StringBuilder zeString = new StringBuilder();
  56. for (int j = 0; j < nameLength - forNeName.length(); j++) {
  57. zeString.append("0");
  58. }
  59. forNeName = "image" + zeString + forNeName + lastName;
  60. } else {
  61. forNeName = "image" + forNeName + lastName;
  62. }
  63. FileUtils.copyFile(files[i], new File(tmpPath + "/" + forNeName));
  64. }
  65. }
  66. }
  67. return nameLength;
  68. }
  69. public static int getLen(int x) {
  70. if (x < 10) return 1;
  71. return getLen(x / 10) + 1;
  72. }
  73. public static int getMakeUpMaxNum(int len) {
  74. int num = 1;
  75. for (int i = 1; i < len; i++) {
  76. num = num * 10;
  77. }
  78. return num - 1;
  79. }
  80. }