WPF画布到具有透明背景的动画gif,显示在svg画布上



在我的web项目中,我需要将XAML帧动态渲染为动画gif。它现在可以工作了——我用以下代码将每个帧渲染为png:

        // Save current canvas transform
        var transform = surface.LayoutTransform;
        // reset current transform (in case it is scaled or rotated)
        surface.LayoutTransform = null;
        // Get the size of canvas
        var size = new System.Windows.Size(surface.Width, surface.Height);
        // Measure and arrange the surface
        // VERY IMPORTANT
        surface.Measure(size);
        surface.Arrange(new Rect(size));
        // Create a render bitmap and push the surface to it
        var renderBitmap =
            new RenderTargetBitmap(
                (int)size.Width,
                (int)size.Height,
                96d,
                96d,
                PixelFormats.Pbgra32);
        renderBitmap.Render(surface);
        Bitmap bmp;
        // Create a file stream for saving image
        using (var stream = new MemoryStream()) {
            // Use png encoder for our data
            var encoder = new PngBitmapEncoder();
            // push the rendered bitmap to it
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            // save the data to the stream
            encoder.Save(stream);
            bmp = new Bitmap(stream);
        }
        return bmp;

然后使用MagickImage创建动画gif。但当我把它放在网页上(svg画布上)时,背景不是透明的,而是黑色的。如何使其透明?

您必须确保设置了透明标志。您还必须获得透明颜色的索引,并确保也设置了该索引,确保所有透明像素都为透明颜色索引编制索引(请注意,透明像素可以具有任何RGB值)。

我看了一下MagickImage文档,它没有给我任何GIF信息。然后我又看了一遍你的代码,你编码的是png而不是gif。我找到了gif信息,也许你做了一个中间步骤。API没有任何关于GIF的内容,我所能做的就是给你GIF数据块的详细信息,这样你就可以自己找到正确的标志和设置。

您必须更改的内容在每个图像数据块开始之前的GCE块中。

透明的正确设置

 options.delay = 2; //what ever you want Dont go under 2 as many gif renderers are limited to 50frames a second.  Frame delay in 1/100 secs
 options.transparentFlag = true;  // This must be true for transparent
 options.transparentIndex = transColour; //The 8 bit index of the transparent colour
 // this must be set correctly for transparent to work.
 options.dispose = 3; //use 3 or 2 if you want transparency;

写入GCE块

// the following is writing the GCE block that must be included before every image
// write writes an array or single byte to the stream
// shortData creates a  Little-endian 16 bit short (high byte first) byte array
//
GCE_ID = 0xf9; // GCE block indentifier
GCE_size = 4;  // block length
write([0x21 , GCE_ID , GCE_size]); // extension introducer
write(
    0 +                             // bits 8:7 reserved
    (options.dispose << 2) +        // bits 5:4:3:2 disposal method
    (options.transparentFlag?1:0)); // 1 transparency flag
write( shortData(options.delay) ); // delay x 1/100 sec
write( options.transparentIndex ); // transparent color index
write(0);                          // block terminator
// image block follows

不是你想要的那种答案,但我不认为你在保存礼物。如果你超过了,你应该能够找到要设置的内容,以便将正确的GCE块写入gif文件。最后一点。背景颜色使用不同于透明索引的颜色索引。我保留全局RGB查找表的最后两个索引用于背景和透明。

最新更新