Created
September 21, 2024 16:43
-
-
Save pavlovmilen/69803149e25c3f14cd6d0a30785ceb0f to your computer and use it in GitHub Desktop.
Get image binary data with content type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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