【问题标题】:Is there a way to keep the alpha channel when compiling bmp's to a video file in c#?在c#中将bmp编译为视频文件时,有没有办法保留alpha通道?
【发布时间】:2019-09-07 22:04:03
【问题描述】:

我正在尝试在保持透明背景的同时录制动画。

我使用 Windows 窗体在具有透明背景的图片框中运行了一些动画。我将每一帧转换为带有 alpha 通道的 bmp,然后尝试将它们拼接在一起以获得仍然具有透明背景的视频。 例如,我有 60 帧的正方形图形向右移动。 为了创建视频,我使用了 Accord Video 库。 (Accord.Video.FFMPEG)

public Form1()
        {
            InitializeComponent();
            pictureBox1.Paint += new PaintEventHandler(PictureBox1_Paint);

            // create instance of video writer
            VideoFileWriter writer = new VideoFileWriter();
            // create new video file
            writer.Open("test.avi", pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, 60, VideoCodec.H264);
            // create a bitmap to save into the video file
            Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            for (int i = 0; i < 60; ++i)
            {
                pictureBox1.Invalidate();
                pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
                writer.WriteVideoFrame(bmp);
                this.x += 2;
            }
            writer.Close();
        }

        private void PictureBox1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            SolidBrush brush = new SolidBrush(Color.Blue);
            g.FillRectangle(brush, new Rectangle(new Point(x, 50), new Size(50, 50)));
        }

        private int x = 50;

根据我的阅读,H.264 编解码器支持 Alpha 通道,但结果是它只是将每一帧堆叠在一起,背景变成黑色(而不是透明)。

screenshot of the result

【问题讨论】:

  • 不要混淆 Bitmap(一个 gdi+ 对象)和 bmp(一个文件格式)!另外:DrawToBitmap 的结果不能有 alpha 通道,即使你声明了一个,因为它是控制表面!而是自己使用 GDI+ DrawImage 绘制您想要的图层!
  • 您正在使用 h264 编码,这是一种不支持 Alpha 通道的编解码器,因此无法将该数据保存在您的视频文件中。您将需要一个支持 Alpha 通道的编解码器,并在您的管道的其余部分支持该编解码器和 Alpha 通道。

标签: c# alpha video-codecs


【解决方案1】:

正如 Anon Coward 所说,H.264 编解码器不支持 Alpha 通道。 遗憾的是,Accord Video 库中的编解码器都不支持 alpha 通道,因此我将所有帧写入一个目录,然后使用 FFMPEG 将它们一起编译成一个视频文件。我使用的是 PNG 视频编解码器。

TaW 还指出,我将 BitMap 与 bmp 混淆了,我通过将所有内容绘制到 BitMap 并使用该 BitMap 作为框架来解决这个问题。为了在图片框上绘图,我使用了 DrawImage。

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多