Lempkin February 2016

How to display image returned by WS?

I request a WS which returns an image.

 HttpWebResponse response = (HttpWebResponse)request.GetResponse();

I can see that in the HttpWebResponse contentType is image/jpeg. I would like to display this image in my view, but I don't know how. I don't want to write this image in a concrete file on the HDD.
What do i have to extract from the HttpWebResponse, do I have to cast it in byte[], in a File, or so?
And how can I display <img> in my view, what should I put for src, as the file will not really exist?

<img src="???" />

Edit : This is what I've done so far :

In controller :

 ...
byte[] responseByte = null;
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 Stream dataStream = response.GetResponseStream();
 long streamLength = GetStreamLength(dataStream);
 responseByte = new byte[streamLength];
 dataStream.Read(responseByte, 0, (int)streamLength);
 productDTO.thumbnail = responseByte;

And in the view :

 @{
      var base64 = Convert.ToBase64String(@item.thumbnail);
      var imgSrc = String.Format("data:image/jpeg;base64,{0}", base64);
  }
  <img src="@imgSrc" />

But I get a broken link for image and @imgSrc contains only

<img src="data:image/jpeg;base64,AAAAAA.....AAAAAAAAAAA">

Answers


Kamil Stachowiak February 2016

You can use base64 format image in src.

It looks like this:

    <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

You can see this working here:

http://jsfiddle.net/hpP45/1763/


Lempkin February 2016

Finally that's what i've done (that's a mix of above answers and others found on others topics) :

Controller:

...
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
wsResponseAsImg = Image.FromStream(response.GetResponseStream());

byte[] imgBytes = turnImageToByteArray(wsResponseAsImg);
string imgString = Convert.ToBase64String(imgBytes);
string responseImgToBase64 = String.Format("data:image/jpeg;base64," + imgString);
 productDTO.thumbnail = responseImgToBase64;

 ...
 }


    private byte[] turnImageToByteArray(System.Drawing.Image img)
    {
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms.ToArray();
    }

View :

...
<img src="@item.thumbnail" />
...

Thanks for helping :)

Post Status

Asked in February 2016
Viewed 1,045 times
Voted 12
Answered 2 times

Search




Leave an answer