简体   繁体   中英

c# uwp winrt Image or Bitmap Image to base64

BitmapImage bitmap = new BitmapImage(new Uri("ms-appx:///Assets/Video.png"));

I am trying to convert a bitmap image to base64 to string on universal app.Do have any idea about how it can be ?

You have to convert your image to bytes. Then you can call Convert.ToBase64String.

There's couple good sources of information for this:

Reading and Writing Base64 in the Windows Runtime

Codepaste

To summarize these, to convert Image to base64 , you should be able to use the following method:

        var bitmap = new RenderTargetBitmap();
        await bitmap.RenderAsync(ImageControl);

        var image = (await bitmap.GetPixelsAsync()).ToArray();
        var width = (uint) bitmap.PixelWidth;
        var height = (uint)bitmap.PixelHeight;

        double dpiX = 96;
        double dpiY = 96;

        var encoded = new InMemoryRandomAccessStream();
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded);

        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, width, height, dpiX, dpiY, image);
        await encoder.FlushAsync();
        encoded.Seek(0);

        var bytes = new byte[encoded.Size];
        await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length);

        var base64String = Convert.ToBase64String(bytes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM