1

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?

Darrick Herwehe
  • 3,553
  • 1
  • 21
  • 30
D.K.
  • 396
  • 3
  • 6
  • 21
  • Could you define "not working"? – Broots Waymb Mar 28 '18 at 12:33
  • The App is crashing, and debugger not working as well. – D.K. Mar 28 '18 at 12:34
  • Are you compiling in debug or release mode? Are code optimizations turned on or off? If you're in release or if optimizations are on debugging won't behave how you're expecting it to (if at all). – Broots Waymb Mar 28 '18 at 12:42
  • Have you tried setting breakpoints or running your code line by line? Would give you a hint where the problem actually is. – Norman Mar 28 '18 at 12:42
  • 1. for Broot's question: In debug mode 2. For Norman: I tried. thing is the breakpoint gets fired then when I execute line by line the, the app freezes and gets closed. – D.K. Mar 28 '18 at 16:19
  • There are lots of potential issues in the code like for example not disposing streams. Have you tried to debug your app? Does the code even gets into those lines? Some help you may also find [at this question](https://stackoverflow.com/q/21325661/2681948). – Romasz Mar 28 '18 at 16:58

1 Answers1

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

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

This worked for me.

D.K.
  • 396
  • 3
  • 6
  • 21