如何用媒体服务裁剪视频文件 - .NETHow to crop video files with Media Services - .NET

媒体服务徽标 v3media services logo v3


可以使用媒体服务裁剪输入视频。You can use Media Services to crop an input video. 裁剪是指在视频帧内选择一个矩形窗口并且只编码该窗口内的像素的过程。Cropping is the process of selecting a rectangular window within the video frame, and encoding just the pixels within that window. 下图可帮助说明该过程。The following diagram helps illustrate the process.

预处理阶段Pre-processing stage

裁剪是预处理阶段,因此,编码预设​​值中的裁剪参数适用于输入视频 。Cropping is a pre-processing stage, so the cropping parameters in the encoding preset apply to the input video. 编码是后续阶段,因此,宽度/高度设置适用于 经过预先处理 的视频,而非原始视频。Encoding is a subsequent stage, and the width/height settings apply to the pre-processed video, and not to the original video. 计划预设时,请执行以下操作:When designing your preset, do the following:

  1. 根据原始输入视频选择裁剪参数Select the crop parameters based on the original input video
  2. 根据裁剪后的视频选择编码设置。Select your encode settings based on the cropped video.

警告

如果编码设置与裁剪后的视频不匹配,输出会不如预期。If you do not match your encode settings to the cropped video, the output will not be as you expect.

比如你输入的视频分辨率为 1920x1080 像素(16:9 纵横比),不过因为左侧和右侧有黑色长条(圆柱框),导致包含活动视频的区域只有 4:3 窗口或 1440x1080 像素。For example, your input video has a resolution of 1920x1080 pixels (16:9 aspect ratio), but has black bars (pillar boxes) at the left and right, so that only a 4:3 window or 1440x1080 pixels contains active video. 可以裁剪黑色条,并对 1440x1080 区域编码。You can crop the black bars, and encode the 1440x1080 area.

转换代码Transform code

下面的代码段演示如何在.NET 中编写转换码来裁剪视频。The following code snippet illustrates how to write a transform in .NET to crop videos. 代码假设你有一个要处理的本地文件。The code assumes that you have a local file to work with.

  • “Left”是裁剪的最左侧位置。Left is the left-most location of the crop.
  • “Top”是裁剪最顶部的位置。Top is the top-most location of the crop.
  • “Width”为裁剪的最终宽度。Width is the final width of the crop.
  • “Height”为剪裁的最终高度。Height is the final height of the crop.
var preset = new StandardEncoderPreset

    {

        Filters = new Filters

        {                   

            Crop = new Rectangle

            {

                Left = "200",

                Top = "200",

                Width = "1280",

                Height = "720"

            }

        },

        Codecs =

        {

            new AacAudio(),

            new H264Video()

            {

                Layers =

                {                           

                    new H264Layer

                    {

                        Bitrate = 1000000,

                        Width = "1280",

                        Height = "720"

                    }

                }

            }

        },

        Formats =

        {

            new Mp4Format

            {

                FilenamePattern = "{Basename}_{Bitrate}{Extension}"

            }

        }

    }