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
352 stars 56 forks source link

ImageData.Stride calculation #135

Open MAtt5816 opened 7 months ago

MAtt5816 commented 7 months ago

I'm using example code for WPF:

using System.Windows.Media.Imaging;
...
// ImageData -> BitmapSource (unsafe)
public static unsafe BitmapSource ToBitmap(this ImageData bitmapData)
{
    fixed(byte* ptr = bitmapData.Data)
    {
        return BitmapSource.Create(bitmapData.ImageSize.Width, bitmapData.ImageSize.Height, 96, 96, PixelFormats.Bgr32, null, new IntPtr(ptr), bitmapData.Data.Length, bitmapData.Stride);
    }
}

// BitmapSource -> ImageData (safe)
public static ImageData ToImageData(this BitmapSource bitmap)
{
    var wb = new WriteableBitmap(bitmap);
    return ImageData.FromPointer(wb.BackBuffer, ImagePixelFormat.Bgra32, wb.PixelWidth, wb.PixelHeight);
}

I use ToImageData() to save bitmaps to .avi file. Then I decode .avi with ToBitmap() and I get the error code "Value does not fall within the expected range". I concluded that the error is in the stride calculation. For me, for an image width of 1076 px, stride in bitmapData.Stride is calculated 3228 (3 * width) but should be 4304 px (4 * width).