Convert Image to Base64 string

杀马特。学长 韩版系。学妹 提交于 2020-01-25 01:29:06

问题


I am trying to convert an Image file to Base64 string in UWP with StorageFile Here's the method I have:

public async Task<string> ToBase64String(StorageFile file)
{
    var stream = await file.OpenAsync(FileAccessMode.Read);
    var decoder = await BitmapDecoder.CreateAsync(stream);
    var pixels = await decoder.GetPixelDataAsync();
    var bytes = pixels.DetachPixelData();
    return await ToBase64(bytes, (uint)decoder.PixelWidth, (uint)decoder.PixelHeight, decoder.DpiX, decoder.DpiY);
}

and ToBase64 goes like this:

private async Task<string> ToBase64(byte[] image, uint pixelWidth, uint pixelHeight, double dpiX, double dpiY)
{
    //encode
    var encoded = new InMemoryRandomAccessStream();
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded);
    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, pixelWidth, pixelHeight, dpiX, dpiY, image);
    await encoder.FlushAsync();
    encoded.Seek(0);

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

    return System.Convert.ToBase64String(bytes);
}

and calling it from my MainPage.xaml.cs

StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
string square_b64 = converter.ToBase64String(await storageFolder.GetFileAsync("Image.png")).Result;

However, This is not working. Any Heads up?


回答1:


StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file1 = await storageFolder.GetFileAsync("Image.png");

string _b64 = Convert.ToBase64String(File.ReadAllBytes(file1.Path));

This worked for me.



来源:https://stackoverflow.com/questions/49534642/convert-image-to-base64-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!