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?
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file1 = await storageFolder.GetFileAsync("Image.png");
string _b64 = Convert.ToBase64String(File.ReadAllBytes(file1.Path));
This worked for me.