you are almost there, use the GetByteArrayAsync:
private async Task<string> GetImageAsBase64Async(string url) // return Task<string>
{
using (var client = new HttpClient())
{
var bytes = await client.GetByteArrayAsync(url); // there are other methods if you want to get involved with stream processing etc
var base64String = Convert.ToBase64String(bytes);
return base64String;
}
}
UPD
as @Fildor points out, you want to instantiate your HttpClient once and inject it into the function. A very naive way to do that would be to use an extension method:
void Main()
{
HttpClient client = new HttpClient(); // can reuse
client.GetImageAsBase64("...");
client.GetImageAsBase64("...");
client.GetImageAsBase64("...");
}
static class HttpclientExtensions
{
public static async Task<string> GetImageAsBase64(this HttpClient client, string url)
{
var bytes = await client.GetByteArrayAsync(url);
return Convert.ToBase64String(bytes);
}
}