radek-k / FFMediaToolkit

FFMediaToolkit is a cross-platform video decoder/encoder library for .NET that uses FFmpeg native libraries. It supports video frames extraction, reading stream metadata and creating videos from bitmaps in any format supported by FFmpeg.
MIT License
362 stars 56 forks source link

How to convert ImageData to SkiaSharp.SkiBitmap #123

Open SamGuoMsft opened 2 years ago

SamGuoMsft commented 2 years ago

Try to convert How to convert ImageData to SkiaSharp.SkiBitmap by using SKBitmap.Decode(imageData.Data, new SKImageInfo { Height = imageData.ImageSize.Height, Width = imageData.ImageSize.Width }), but it keep failing.

Does anyone know how to convert ImageData to SkiBitmap?

hey-red commented 2 years ago

Here is example. It's is not optimized, but should work.

using System.Runtime.InteropServices;

using FFMediaToolkit.Decoding;
using FFMediaToolkit.Graphics;

using SkiaSharp;

var file = MediaFile.Open(@"/path/to/file.mp4", new MediaOptions
{
    VideoPixelFormat = ImagePixelFormat.Rgba32 // Set skia supported pix format
});

if (file.Video.TryGetNextFrame(out var imageData))
{
    var gcHandle = GCHandle.Alloc(imageData.Data.ToArray(), GCHandleType.Pinned);

    using var bitmap = new SKBitmap();
    var imageInfo = new SKImageInfo(imageData.ImageSize.Width, imageData.ImageSize.Height, SKColorType.Rgba8888, SKAlphaType.Unpremul);

    bitmap.InstallPixels(imageInfo, gcHandle.AddrOfPinnedObject(), imageInfo.RowBytes, delegate { gcHandle.Free(); });

    // Save to file
    using var fs = File.OpenWrite(@"/path/to/image.png");
    bitmap.Encode(fs, SKEncodedImageFormat.Png, 100);
}