How To Return An Image Result From Web API Using .NET Core

Introduction
 
You have seen earlier how to return a string response or an object response using Web API. Today, we will learn how to return an image from a web API. We will use .NET Core as the framework to develop this Web API. I will be using Visual Studio 2017 for this development activity. By the end of this application, you will be able to render the image from a text through web API and an image file from your server or other hosted location. I create my application with understanding that my readers are just beginners so if you already know a few things, please skip the first few steps and see directly the actual logic. I personally believe in writing complete articles so that you  do not need to go anywhere while setting up this subject to go live.
 
Let's start setting it up.
 
Step 1
 
Open your Visual Studio. In my case, I am using Visual Studio 2017. After opening the VS, click on File >> NEW >> Project as below.
 
How To Return An Image Result From Web API Using .NET Core
So, this will open another window as below.
 
How To Return An Image Result From Web API Using .NET Core
 
Step 2
 
In this window, we have selected web, then clicked on ASP.NET Core Web Application. Give a name to the project as I have given KapilDGImage. You can choose a different location to save your project and give a solution name.
 
By default, VS takes the solution name same as the Project name while we create our first project. Click OK.
 
Once you click OK, the following window opens.
 
How To Return An Image Result From Web API Using .NET Core
 
Step 3
 
Click on OK again. We are choosing "no authentication" over here. You can choose authentication later, after the concept of today's subject is clear. Maybe later, I will cover all kinds of authentications. So, after this step, your Web API project will be created using .NET Core. You will see your solution directory structure similar to the one given below.
 
 How To Return An Image Result From Web API Using .NET Core
 
This is the default structure of the Web API template project in .NET Core. You can see the contents of Startup.cs file and Program.cs file.
 
These files are actually responsible for running your project. We won't do any changes in these two files because today, our motive is to render an image using Web API. So, we will directly move towards ValuesController.cs files which are actually responsible for rendering the outputs and how a particular url will render and all its processing.
 
Step 4
 
We will do changes in ValuesController.cs file as given below.
  1. using System;  
  2. using System.Drawing;  
  3. using System.IO;  
  4. using Microsoft.AspNetCore.Mvc;  
  5.   
  6.   
  7. namespace KapilDGImage.Controllers  
  8. {  
  9.     [Route("api/[controller]")]  
  10.     [ApiController]  
  11.     public class ValuesController : ControllerBase  
  12.     {  
  13.         // GET api/values  
  14.         [HttpGet]  
  15.         public IActionResult Get(string type)  
  16.         {  
  17.             Byte[] b;  
  18.             if(type == null)  
  19.             {  
  20.                 return Content("Hi there is no type value given. Please enter picturefromtext or hostedimagefile in type parameter in url");  
  21.             }  
  22.             if (type.Equals("picturefromtext"))  
  23.             {  
  24.                 Image image = DrawText("Kapil Dev Gaur"new Font(FontFamily.GenericSansSerif, 15), Color.DarkBlue, Color.Cornsilk);  
  25.                 b = ImageToByteArray(image);  
  26.             }  
  27.             else if(type.Equals("hostedimagefile"))  
  28.             {  
  29.                 b = System.IO.File.ReadAllBytes("c:\\users\\kapildevg\\source\\repos\\KapilDGImage\\KapilDGImage\\Images\\Kapil_Dev_Google.jpg");  
  30.             }  
  31.             else  
  32.             {  
  33.                 return Content("No action is defined for this type value");  
  34.             }  
  35.             return File(b, "image/jpeg");  
  36.         }  
  37.   
  38.         // GET api/values/5  
  39.         [HttpGet("{id}")]  
  40.         public ActionResult<string> Get(int id)  
  41.         {  
  42.             return "value";  
  43.         }  
  44.   
  45.         // POST api/values  
  46.         [HttpPost]  
  47.         public void Post([FromBody] string value)  
  48.         {  
  49.         }  
  50.   
  51.         // PUT api/values/5  
  52.         [HttpPut("{id}")]  
  53.         public void Put(int id, [FromBody] string value)  
  54.         {  
  55.         }  
  56.   
  57.         // DELETE api/values/5  
  58.         [HttpDelete("{id}")]  
  59.         public void Delete(int id)  
  60.         {  
  61.         }  
  62.   
  63.         public Image DrawText(String text, Font font, Color textColor, Color backColor)  
  64.         {  
  65.             //first, create a dummy bitmap just to get a graphics object  
  66.             Image img = new Bitmap(1, 1);  
  67.             Graphics drawing = Graphics.FromImage(img);  
  68.   
  69.             //measure the string to see how big the image needs to be  
  70.             SizeF textSize = drawing.MeasureString(text, font);  
  71.   
  72.             //free up the dummy image and old graphics object  
  73.             img.Dispose();  
  74.             drawing.Dispose();  
  75.   
  76.             //create a new image of the right size  
  77.             img = new Bitmap((int)textSize.Width, (int)textSize.Height);  
  78.   
  79.             drawing = Graphics.FromImage(img);  
  80.   
  81.             //paint the background  
  82.             drawing.Clear(backColor);  
  83.   
  84.             //create a brush for the text  
  85.             Brush textBrush = new SolidBrush(textColor);  
  86.   
  87.             drawing.DrawString(text, font, textBrush, 0, 0);  
  88.   
  89.             drawing.Save();  
  90.   
  91.             textBrush.Dispose();  
  92.             drawing.Dispose();  
  93.   
  94.             return img;  
  95.   
  96.         }  
  97.         public byte[] ImageToByteArray(System.Drawing.Image imageIn)  
  98.         {              
  99.                 MemoryStream ms = new MemoryStream();  
  100.                 imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);  
  101.                 return ms.ToArray();              
  102.         }  
  103.     }  
  104. }  
Step 5
 
Now, when you run this application, it opens in Chrome (for me). It might open in another browser based on the availability or settings. The first output comes like this when no type parameter is sent to the URL.
 
How To Return An Image Result From Web API Using .NET Core
 
Step 6
 
After this, assign a type parameter in the URL as picturefromtext. This will render an image from the text which we have set in the controller. We can also take this from the URL based on our requirement. So, after you hit the URL, you will get the following response.
 
How To Return An Image Result From Web API Using .NET Core 
 
Here, you will see that an image has been created in the controller using the text Kapil Dev Gaur and has been rendered on the browser.
 
Excuse me for the styles. You can make it as beautiful as you want by the code written in the controller. So, this is when we are generating and rendering the image from the text.
 
Step 7
 
Now, let us change the parameter type to hostedimagefile. This will show you an image that is hosted in your application. You can put any image over here or put a URL taken from the web. It shows the output as below.
 
How To Return An Image Result From Web API Using .NET Core 
 
I have added the above image in the Images directory of this project. You can add any other image and change your ValueController.cs file accordingly.
 
Applications of this concept
 
This is a very important aspect. Now that you know this concept, where can you use it? You can use it for the requirements like below.
  1. You can create Website View and Page View Counter Images and render on your webpages.
  2. You can create greeting cards application where you ask your user names and occassion etc and you in return render an awesome greeting image for him/her.
  3. You can render images on any platform which can consume your Web API.
  4. You can render a user image and other images easily. 
Conclusion
 
I hope all of you would be able to perform complete steps explained in this write-up. You may also need to download and install a NuGet package in your project dependency for this image-handling thing - System.Drawing.Common(4.5.1).  If you liked this simple concept, give it a thumbs up or feedback in comments.


Similar Articles