Skip to content

Instantly share code, notes, and snippets.

@pavlovmilen
Created September 21, 2024 16:43
Show Gist options
  • Save pavlovmilen/69803149e25c3f14cd6d0a30785ceb0f to your computer and use it in GitHub Desktop.
Save pavlovmilen/69803149e25c3f14cd6d0a30785ceb0f to your computer and use it in GitHub Desktop.
Get image binary data with content type
public async Task<ImageResponse> GetImageDataAsync(string imageLink)
{
try
{
var imageResponse = new ImageResponse();
using var response = await _httpClient.GetAsync(imageLink);
response.EnsureSuccessStatusCode();
// Read the content as a byte array
byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();
imageResponse.BinaryData = new BinaryData(imageBytes);
string mediaType = response.Content.Headers.ContentType?.MediaType;
if (string.IsNullOrEmpty(mediaType))
{
mediaType = "application/octet-stream";
}
imageResponse.ContentType = mediaType;
return imageResponse;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in GetImageBytesAsync");
throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment