流畅的ffmpeg宽高比与裁剪率

问题描述 投票:0回答:1

我在16:9、1:1和9:16之间改变宽高比时遇到了问题,使用 熟练的ffmpeg当我试图从16:9改变到9:16,我有点收到一个挤压的视频,但实际上我想额外的部分应该被删除。

我尝试了许多组合。

FFmpeg() .input(video) .size("608x?") .aspect("9:16") .output(tempFile) .run();

我的输入是16: 9的视频1920x1080My input 16:9 video 1920x1080

.

我的预期结果 9:16 视频 608x1080

My Expected result 9:16 video 608x1080

node.js ffmpeg crop aspect-ratio fluent-ffmpeg
1个回答
1
投票

最理想的解决方案,我来到了。我想出了最理想的解决方案: fluent-ffmpeg 不提供任何内置的方法来裁剪和缩放视频,这就是为什么我们需要自己实现它。

第1步:我们需要计算一个中间的裁剪分辨率,以达到目标长宽比,要么通过裁剪额外的(横向到纵向)或通过添加黑条(纵向到横向),以避免挤压或拉伸的视频)。

注意:我们也可以添加一个很好的模糊效果的情况下,纵向到横向,但这将增加一个额外的步骤(ffmpeg模糊过滤器需要)。

第二步:我们将简单地放大或缩小到我们的目标分辨率。

这段代码似乎太长了,但相信我,它很简单,而且分为很多方法。从底部开始理解。忽略 types 如果你想 JavaScript 版本。

只要运行这段代码,它就会为你裁剪一个视频。

import * as FFmpeg from "fluent-ffmpeg";

function resizingFFmpeg(
  video: string,
  width: number,
  height: number,
  tempFile: string,
  autoPad?: boolean,
  padColor?: string
): Promise<string> {
  return new Promise((res, rej) => {
    let ff = FFmpeg().input(video).size(`${width}x${height}`);
    autoPad ? (ff = ff.autoPad(autoPad, padColor)) : null;
    ff.output(tempFile)
      .on("start", function (commandLine) {
        console.log("Spawned FFmpeg with command: " + commandLine);
        console.log("Start resizingFFmpeg:", video);
      })
      // .on("progress", function(progress) {
      //   console.log(progress);
      // })
      .on("error", function (err) {
        console.log("Problem performing ffmpeg function");
        rej(err);
      })
      .on("end", function () {
        console.log("End resizingFFmpeg:", tempFile);
        res(tempFile);
      })
      .run();
  });
}

function videoCropCenterFFmpeg(
  video: string,
  w: number,
  h: number,
  tempFile: string
): Promise<string> {
  return new Promise((res, rej) => {
    FFmpeg()
      .input(video)
      .videoFilters([
        {
          filter: "crop",
          options: {
            w,
            h,
          },
        },
      ])
      .output(tempFile)
      .on("start", function (commandLine) {
        console.log("Spawned FFmpeg with command: " + commandLine);
        console.log("Start videoCropCenterFFmpeg:", video);
      })
      // .on("progress", function(progress) {
      //   console.log(progress);
      // })
      .on("error", function (err) {
        console.log("Problem performing ffmpeg function");
        rej(err);
      })
      .on("end", function () {
        console.log("End videoCropCenterFFmpeg:", tempFile);
        res(tempFile);
      })
      .run();
  });
}

function getDimentions(media: string) {
  console.log("Getting Dimentions from:", media);
  return new Promise<{ width: number; height: number }>((res, rej) => {
    FFmpeg.ffprobe(media, async function (err, metadata) {
      if (err) {
        console.log("Error occured while getting dimensions of:", media);
        rej(err);
      }
      res({
        width: metadata.streams[0].width,
        height: metadata.streams[0].height,
      });
    });
  });
}

async function videoScale(video: string, newWidth: number, newHeight: number) {
  const output = "scaledOutput.mp4";
  const { width, height } = await getDimentions(video);
  if ((width / height).toFixed(2) > (newWidth / newHeight).toFixed(2)) {
    // y=0 case
    // landscape to potrait case
    const x = width - (newWidth / newHeight) * height;
    console.log(`New Intrim Res: ${width - x}x${height}`);
    const cropping = "tempCropped-" + output;
    let cropped = await videoCropCenterFFmpeg(
      video,
      width - x,
      height,
      cropping
    );
    let resized = await resizingFFmpeg(cropped, newWidth, newHeight, output);
    // unlink temp cropping file
    // fs.unlink(cropping, (err) => {
    //   if (err) console.log(err);
    //   console.log(`Temp file ${cropping} deleted Successfuly...`);
    // });
    return resized;
  } else if ((width / height).toFixed(2) < (newWidth / newHeight).toFixed(2)) {
    // x=0 case
    // potrait to landscape case
    // calculate crop or resize with padding or blur sides
    // or just return with black bars on the side
    return await resizingFFmpeg(video, newWidth, newHeight, output, true);
  } else {
    console.log("Same Aspect Ratio forward for resizing");
    return await resizingFFmpeg(video, newWidth, newHeight, output);
  }
}

videoScale("./path-to-some-video.mp4", 270, 480);
© www.soinside.com 2019 - 2024. All rights reserved.