0

Is there a way to convert a HTTP Get response into Image() object?

currently i use:

backImage = new Image()
backImage.src = "http://www.example.com/someimage.jpg";

i want to use my web api (which serves HttpResponseMessage):

public HttpResponseMessage GetImage(Guid id)
        {
           // my logic and image extraction
           var file = new FileInfo("path-to-my-image");
           var fileStream = file.OpenRead();
           var response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                response.Content.Headers.ContentLength = file.Length;
                return response;
            }

which i currently invoke via

this.http.get("http://www.example.com/api/GetImage/"+id);

When i test it in Postman i returns the response and renders the image.

I am trying to find out if its possible to convert that response and store it in the Image() object as per example.

Aeseir
  • 7,754
  • 10
  • 58
  • 107
  • 1
    What are you returning in `GetImage` API? – Satpal Apr 18 '17 at 11:48
  • HttpResponseMessage containing the image – Aeseir Apr 18 '17 at 11:49
  • does your method read the `.jpg` file and sent the stream as the respose to the client? – NiRUS Apr 18 '17 at 11:53
  • yea it does, just updated the question showing response – Aeseir Apr 18 '17 at 11:53
  • i guess you dont need `http.get`. Just directly set the URL to the `img.src` like `img.src = "http://www.example.com/api/GetImage/my-id.jpg"` as you are setting all the reqired header values that tell the client that incoming respose is a file of jpg type – NiRUS Apr 18 '17 at 11:59

2 Answers2

1

You can return base64 value of your image:

var returnString = "data:image/jpg;base64,"+Convert.ToBase64String(bytearray);

example on client side:

this.http
 .get("http://www.example.com/api/GetImage/"+id)
 .then(x=>{
    backImage = new Image()
    backImage.src = x;
   //render
});

example of controller:

public object GetImage(Guid id)
{
  string base64String;

  Byte[] bytes = File.ReadAllBytes("path to filename"+id);
  base64String = Convert.ToBase64String(bytes);

  return "data:image/jpg;base64," + base64String;
}
Aeseir
  • 7,754
  • 10
  • 58
  • 107
0

Here is an example using setgetgo API that returns image based on ID

var img = new Image();
var generateImageId = () => Math.ceil(Math.random() * 100000);
img.src = "http://setgetgo.com/randomimage/get.php?key=" + generateImageId();
document.body.appendChild(img)

Working fiddler link


To save the image to disk checkout this SO answer

Community
  • 1
  • 1
NiRUS
  • 3,901
  • 2
  • 24
  • 50