1

I have a ImageSource imageSource, and want to convert to byte array or stream, how?I tried

WriteableBitmap bitmap = imageSource as WriteableBitmap;
var stream = bitmap.PixelBuffer.AsStream();

But bitmap is null...

Vincent
  • 3,124
  • 3
  • 21
  • 40

1 Answers1

0

You should sure the imageSource is WriteableBitmap for it can be BitmapImage or WriteableBitmap ……

If the imageSource is WriteableBitmap that you can write your code.

But if the imageSource is BitmapImage that you should use WriteableBitmapEx

The first is use nuget to download WriteableBitmapEx.

And then you can change it to WriteableBitmap.

 WriteableBitmap image = await BitmapFactory.New(1, 1).FromContent((BitmapImage).UriSource);

And then you can convert WriteableBitmap to stream.

If your imageSource is RenderTargetBitmap that you can use this code.

private async Task<string> ToBase64(RenderTargetBitmap bitmap)
{
    var bytes = (await bitmap.GetPixelsAsync()).ToArray();
    return await ToBase64(bytes, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight);
}

See(Chinese language):https://lindexi.gitee.io/post/win10-uwp-%E8%AF%BB%E5%8F%96%E4%BF%9D%E5%AD%98WriteableBitmap-BitmapImage.html

lindexi
  • 4,182
  • 3
  • 19
  • 65