c#uwp winrt图像或位图图像到base64

时间:2016-04-08 13:51:41

标签: c# windows-runtime win-universal-app

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

我正在尝试将位图图像转换为base64到通用应用程序上的字符串。有任何想法它是怎么回事?

1 个答案:

答案 0 :(得分:0)

您必须将图像转换为字节。然后你可以拨打Convert.ToBase64String.

有很多很好的信息来源:

Reading and Writing Base64 in the Windows Runtime

Codepaste

总结一下,要将图片转换为base64 ,您应该可以使用以下方法:

        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);