Search code examples
androidxamarin.formsbitmapskiasharpskia

How to convert SkiaSharp.SkBitmap to Android.Graphics.Bitmap?


I want to convert PinBitmap (SkiaSharp.SkBitmap) to Android.Graphics.Bitmap. I couldn't find online references, I only tried this in the Android project:

Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeByteArray(myView.PinBitmap.Bytes, 0, myView.PinBitmap.Bytes.Length);

but the bitmap is null.

I'm creating the PinBitmap from a SKCanvasView:

private void SKCanvasView_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
{
    var surface = e.Surface;
    var canvas = surface.Canvas;
    SKImageInfo info = e.Info;

    canvas.DrawLine(10, 10, 10, 200, new SKPaint() { IsStroke = true, Color = SKColors.Green, StrokeWidth = 10 });
    SKBitmap saveBitmap = new SKBitmap();

    // Create bitmap the size of the display surface
    if (saveBitmap == null)
    {
        saveBitmap = new SKBitmap(info.Width, info.Height);
    }
    // Or create new bitmap for a new size of display surface
    else if (saveBitmap.Width < info.Width || saveBitmap.Height < info.Height)
    {
        SKBitmap newBitmap = new SKBitmap(Math.Max(saveBitmap.Width, info.Width),
                                          Math.Max(saveBitmap.Height, info.Height));

        using (SKCanvas newCanvas = new SKCanvas(newBitmap))
        {
            newCanvas.Clear();
            newCanvas.DrawBitmap(saveBitmap, 0, 0);
        }

        saveBitmap = newBitmap;
    }

    // Render the bitmap
    canvas.Clear();
    canvas.DrawBitmap(saveBitmap, 0, 0);

    var customPin = new CustomPin { PinBitmap = saveBitmap };
    Content = customPin;
}

Solution

  • This is easy to do, you just need to have the SkiaSharp.Views NuGet package installed. Then, there are extension methods:

    skiaBitmap = androidBitmap.ToSKBitmap(); 
    androidBitmap = skiaBitmap.ToBitmap(); 
    

    There are also a few others, like: ToSKImage and ToSKPixmap.

    NOTE: these all make copies of the pixel data. To avoid memory issue, you can dispose of the original as soon as the method returns.

    Source: https://forums.xamarin.com/discussion/comment/294868/#Comment_294868