Convert SKBitmap to stream

cjacquelcjacquel FRMember ✭✭✭

Hello,
How to convert a SKBitmap at the screen, to a System.IO.Stream ?
Thx
cjacquel

Posts

  • mattleibowmattleibow ZAXamarin Team Xamurai
    edited August 2017

    You can convert a SKBitmap into a Stream via an SKImage:

    // get the bitmap we want to convert to a stream
    SKBitmap bitmap = ...;
    
    // create an image COPY
    SKImage image = SKImage.FromBitmap(bitmap);
    // OR
    // create an image WRAPPER
    SKImage image = SKImage.FromPixels(bitmap.PeekPixels());
    
    // encode the image (defaults to PNG)
    SKData encoded = image.Encode();
    
    // get a stream over the encoded data
    Stream stream = encoded.AsStream();
    

    Is this what you are looking for?

  • cjacquelcjacquel FRMember ✭✭✭

    Yes, thx, and what about to convert SKCanvasView to stream ?

  • mattleibowmattleibow ZAXamarin Team Xamurai

    SKCanvasView is not really anything more that a view that just displays an canvas (created for you in the paint cycle`.
    To capture the drawn bitmap, you can get an image at the end of the paint method via the surface:

    SKSurface surface = e.Surface;
    SKImage image = e.Surface.Snapshot();
    
  • GMGMGMGM ARMember ✭✭

    @mattleibow does Skia support saving the SKBitmap with a specified dpi resolution? I see that a after creating a SKBitmap and saving it to png, it is set to 96 dpi. I need to create higher resolution images when saving the SKBitmap... any hint on this topic? thanks in advance

  • GMGMGMGM ARMember ✭✭

    @mattleibow does Skia support saving the SKBitmap with a specified dpi resolution? I see that a after creating a SKBitmap and saving it to png, it is set to 96 dpi. I need to create higher resolution images when saving it. Is it possible?

  • mattleibowmattleibow ZAXamarin Team Xamurai
  • dsynodsyno Member ✭✭
    edited May 15

    @mattleibow From your code above, which consumes less memory?

    // create an image COPY
    SKImage image = SKImage.FromBitmap(bitmap);
    // OR
    // create an image WRAPPER
    SKImage image = SKImage.FromPixels(bitmap.PeekPixels());
    
  • mattleibowmattleibow ZAXamarin Team Xamurai

    they are mostly the same, but if the bitmap is immutable, then FromBitmap will copy the pixel data. FromPixels knows nothing except a chunk of pixel data, so it never copies.

    If the bitmap is NOT immutable, then they both just use the data without a copy.

  • MarkZhukovskyMarkZhukovsky USMember ✭✭

    Hey @mattleibow You seem like a real SkiaSharp pro, would you mind taking a look at the issue I raised below? It may just be something specific to that library but if not would really appreciate a tip to make it work. Thanks!
    https://github.com/aloisdeniel/Microcharts/issues/109

Sign In or Register to comment.