Search code examples
c#bitmapasp.net-corerest-client

Converting IRestResponse to "image/jpg" File


I'm trying to pull an image from an API and return to the DOM through the File() method.

Here's what I have so far..

HomeController.cs:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult ImageFromPath()
    {
        var client = new RestClient("http://{{MYIPADDRESS}}/cgi-bin/snapshot.cgi?channel0=");
        var request = new RestRequest(Method.GET);
        request.AddHeader("postman-token", "random-postman-token");
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("authorization", "Digest username=\"MYUSERNAME\", realm=\"MYENCRYPTEDPASS\", nonce=\"LONGSTRING\", uri=\"/cgi-bin/snapshot.cgi?channel0\", response=\"RESPONSESTRING\", opaque=\"\"");
        IRestResponse response = client.Execute(request);(response.RawBytes);

        return File(response, "image/jpg");
    }
}

The only problem here, is that the error on the return statement, response shows

cannot convert from 'RestSharp.IRestResponse' to 'byte[]'


When I was pulling the image from the local file system, it was easier and worked, here was my working code for HomeController.cs

public ActionResult ImageFromPath(string path)
{
    var ms = new MemoryStream();
    using (Bitmap bitmap = new Bitmap(path))
    {
        var height = bitmap.Size.Height;
        var width = bitmap.Size.Width;

        bitmap.Save(ms, ImageFormat.Jpeg);
    }

    ms.Position = 0;
    return File(ms, "image/jpg");
}

Here's how I was pulling it in my front end (Index.cshtml):

<img src="@Url.Action("ImageFromPath", new { path = Request.MapPath("~/img/1.jpg") })" />

Solution

  • This line here:

    return File(response, "image/jpg");
    

    You are passing it response which is of type IRestResponse (a type from RestSharp).

    Why would the built in MVC File method know of RestSharp? File() takes a byte array and a string MIME type.

    Try:

    return File(response.RawBytes, "image/jpg");
    

    RawBytes is a byte array of the raw response from your HTTP Request. If your API is returning a byte array of an image, this is what you need to pass to your file method.