Question

In WindowsStoreApps i want to convert an Local Image from solution explorer to byte array and then to base64 string.please guide me.The code I have tried so far is as below.

public async Task<string> ToBase64()
{
  Byte[] ByteResult = null;

  string bs64 = null;
  if (url != null)
  {
      HttpClient client = new HttpClient();
      ByteResult = await client.GetByteArrayAsync(url);     
  }
  bs64 = Convert.ToBase64String(ByteResult);

  return bs64;
}
Was it helpful?

Solution

Suppose you want to convert an image named MyImage.png from Assets folder then below code will return the base64 string of that image.

private async Task DoWork()
{
    var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/MyImage.png"));
    var b64 = await ConvertStorageFileToBase64String(file);
}

private async Task<string> ConvertStorageFileToBase64String(StorageFile File)
{
    var stream = await File.OpenReadAsync();

    using (var dataReader = new DataReader(stream))
    {
        var bytes = new byte[stream.Size];
        await dataReader.LoadAsync((uint)stream.Size);
        dataReader.ReadBytes(bytes);

        return Convert.ToBase64String(bytes);
    }
} 

OTHER TIPS

Try this piece of code

StorageFile file = <Your  File>;
var bytes = new Byte[0];
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
  var reader = new DataReader(fileStream.GetInputStreamAt(0));
  bytes = new Byte[fileStream.Size];
  await reader.LoadAsync((uint)fileStream.Size);
  reader.ReadBytes(bytes);
}

string imageInStringFormat = Convert.ToBase64String(bytes);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top