I'm trying to pass an image returned from an API in the form of bytes
to the front end to append to the page.
I do NOT want to save the image in the file system, just passing it through this way.
The response is getting returned, but I'm lost as to how to complete this procedure.
Here's my API call:
[HttpGet("api/GetCamImages")]
public async Task<HttpResponseMessage> ImageFromPath()
{
RestClient client = new RestClient("http://MYIPADDRESS/cgi-bin/snapshot.cgi?channel=0");
RestRequest request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic YLKHSouHSSUGh2");
TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();
RestRequestAsyncHandle handle = client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
RestResponse restResponse = (RestResponse)(await taskCompletion.Task);
StringContent myContent = new StringContent(Convert.ToBase64String(restResponse.RawBytes));
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = myContent;
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return response;
}
My js:
$http.get('/api/GetCamImages').then(function (response) {
console.log(response.data);
$("#imgContainer").append('<img src="data:image/png;base64,' + response.data.content + '" />');
});
The console.log
above is displaying this:
To confirm - I realize that the img src above is coming though as [object, Object]
, which is why the image doesn't show. But how would you do this entire call successfully?
I was able to solve this using two ways (both depended on the back end method being altered a bit), where one way was using RestSharp
, and the other used HttpClient
:
Solution 1:
RestClient client = new RestClient("http://MYIPADDRESS/cgi-bin/snapshot.cgi?channel=0");
RestRequest request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic YLKHSouHSSUGh2");
TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();
RestRequestAsyncHandle handle = client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
response = (RestResponse)await taskCompletion.Task;
return "data:image/png;base64," + Convert.ToBase64String(response.RawBytes);
Solution 2:
HttpClient client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage response = await client.GetAsync("http://MYIPADDRESS/cgi-bin/snapshot.cgi?channel=0");
byte[] myBytes = await response.Content.ReadAsByteArrayAsync();
string convertedFromString = Convert.ToBase64String(myBytes);
return "data:image/png;base64," + convertedFromString;