Created
May 14, 2024 18:14
-
-
Save Drewster727/531fe473efec7a9dc31dce3ec1be8ee6 to your computer and use it in GitHub Desktop.
API Photo Response to Base64
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
using System; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
class Program | |
{ | |
static async Task Main(string[] args) | |
{ | |
// Replace with your API endpoint | |
string apiUrl = "https://example.com/your-image-endpoint"; | |
// Create an instance of HttpClient | |
using (HttpClient client = new HttpClient()) | |
{ | |
try | |
{ | |
// Set the Accept header to indicate we expect an image in JPEG format | |
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/jpeg")); | |
// Send a GET request to the API endpoint | |
HttpResponseMessage response = await client.GetAsync(apiUrl); | |
// Ensure the request was successful | |
response.EnsureSuccessStatusCode(); | |
// Read the response content as a byte array | |
byte[] imageData = await response.Content.ReadAsByteArrayAsync(); | |
// Convert the byte array to a base64 string | |
string base64String = Convert.ToBase64String(imageData); | |
// Output the base64 string (or use it as needed) | |
Console.WriteLine(base64String); | |
} | |
catch (HttpRequestException e) | |
{ | |
// Handle any HTTP request exceptions | |
Console.WriteLine($"Request error: {e.Message}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment