.net-coreasp.net-core-mvc2d.net-standardskiasharp

How to convert a byte array to SKBitmap in SkiaSharp?


SKBitmap.Bytes is read only, any suggestion on how to Marshal.Copy a byte array to the SKBitmap? I am using below code snippet but it not working.

Code snippet:

    SKBitmap bitmap = new SKBitmap((int)Width, (int)Height);
    bitmap.LockPixels();
    byte[] array = new byte[bitmap.RowBytes * bitmap.Height];
    for (int i = 0; i < pixelArray.Length; i++)
    {
        SKColor color = new SKColor((uint)pixelArray[i]);
        int num = i % (int)Width;
        int num2 = i / (int)Width;
        array[bitmap.RowBytes * num2 + 4 * num] = color.Blue;
        array[bitmap.RowBytes * num2 + 4 * num + 1] = color.Green;
        array[bitmap.RowBytes * num2 + 4 * num + 2] = color.Red;
        array[bitmap.RowBytes * num2 + 4 * num + 3] = color.Alpha;
    }
    Marshal.Copy(array, 0, bitmap.Handle, array.Length);
    bitmap.UnlockPixels();

Solution

  • You will always have to do some marshaling as the bitmap lives in unmanaged/native memory and the byte array is in managed code. But, you may be able to do something like this:

    // the pixel array of uint 32-bit colors
    var pixelArray = new uint[] {
        0xFFFF0000, 0xFF00FF00,
        0xFF0000FF, 0xFFFFFF00
    };
    
    // create an empty bitmap
    bitmap = new SKBitmap();
    
    // pin the managed array so that the GC doesn't move it
    var gcHandle = GCHandle.Alloc(pixelArray, GCHandleType.Pinned);
    
    // install the pixels with the color type of the pixel data
    var info = new SKImageInfo(2, 2, SKImageInfo.PlatformColorType, SKAlphaType.Unpremul);
    bitmap.InstallPixels(info, gcHandle.AddrOfPinnedObject(), info.RowBytes, null, delegate { gcHandle.Free(); }, null);
    

    This pins the managed memory and passes the pointer to the bitmap. This way, both are accessing the same memory data and there is no need to actually do any conversions (or copying). (It is essential that the pinned memory be unpinned after usage so that the memory can be freed by the GC.)

    Also here: https://github.com/mono/SkiaSharp/issues/416