0

I have an android client and asp.net server and I'm using web api 2. I want to return an image from the server to the client as part of the response, I mean if my response object is:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

now I want my object to look like:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public string Image { get; set; }
}

so that string Image is an image from a folder in the server solution which contains images.

How can I do this?

(I do not know how to define the image object so I defined it to string)

Aviv
  • 5
  • 2
  • Possible duplicate of [Is there a recommended way to return an image using ASP.NET Web API](https://stackoverflow.com/questions/12467546/is-there-a-recommended-way-to-return-an-image-using-asp-net-web-api) – Strikegently Oct 08 '18 at 13:03
  • I want that the image will be part of the response, so that I will return my Product object and not an HttpResponseMessage obejct – Aviv Oct 08 '18 at 13:07
  • Do you want the actual image, or just the path to it on disk? – Stuart Oct 08 '18 at 13:08
  • @Stuart the actual image – Aviv Oct 08 '18 at 13:10

1 Answers1

1

To get he actual image as a string, you will of course need to encode it, you could try base64 encoding it - this will allow you to have it as a string:

byte[] imageBits = System.IO.File.ReadAllBytes(@"/path/to/image");
string imageBase64 = Convert.ToBase64String(imageBits);

Then to display it, you can either use <img src="data:yourBase64StringHere" />, or decode it back into an actual image:

var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(imageBase64)));
Stuart
  • 6,630
  • 2
  • 24
  • 40