Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return base64 encoded images directly from a web api core endpoint

I have seen these SO answers:

  • Return an image from asp.net web api core as IActionResult
  • Response.Body.WriteAsync base64 string not working

but these either serve physical files directly or serve from a byte array.

Please is there a way for our Web API Endpoint to return content-type: image/png directly from data:image/png;base64,(our base64 string)

like image 912
Charles Okwuagwu Avatar asked Jul 01 '17 10:07

Charles Okwuagwu


2 Answers

It is quite straight forward to read a file from a folder. The trick is to use IHostingEnvironment in ASP.NET Core to get the current web root path.

FilesController

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace DemoWebApiCore.Controllers
{
    [Route("api/[controller]")]
    public class FilesController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public FilesController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        // GET api/files/sample.png
        [HttpGet("{fileName}")]
        public string Get(string fileName)
        {
            string path = _hostingEnvironment.WebRootPath + "/images/" + fileName;
            byte[] b = System.IO.File.ReadAllBytes(path);
            return "data:image/png;base64," + Convert.ToBase64String(b);
        }
    }
}

Usage

HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace DemoWebApiCore.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
    }
}

Index.cshtml

<html>
<body>
    <img id="sample-img" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var url = "/api/files/sample.png";
            $.get(url, function (data) {
                console.log(data);
                $("#sample-img").attr('src', data);
            });
        })
    </script>
</body>
</html>
like image 111
Win Avatar answered Nov 06 '22 05:11

Win


If you want to return images as base64 string you can do it like this:

public IHttpActionResult GetImage()
{
    var image = GetImageData();
    var base64 = Convert.ToBase64String(image);

    return Ok(base64);
}
like image 44
ctyar Avatar answered Nov 06 '22 06:11

ctyar