2

I have a problem that when i call my API to get the image, i get the image in binary. I think so...

ImageConverter imageConverter = new ImageConverter();

byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_Obj.GetImage(), typeof(byte[]));

MemoryStream dataStream = new MemoryStream(resourceByteArray);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(dataStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/" + parameters.ImageFormat);

The frontend code.

$("#formoid").submit(function (event) {

/* stop form from submitting normally */
event.preventDefault();

/* get some values from elements on the page: */
var $form = $(this),
url = $form.attr('action');
/* Send the data using post */
var posting = $(this).serialize();

$.ajax({
type: "POST",
url: url,
data: posting
}).done(function (data) {
$('#output').html('<img src="data:image/PNG;base64' + data + '" />');
});
});

The final result is:

<img src="data:image/PNG;base64�PNG

���
IHDR�����@��������sRGB�������gAMA�����a���   pHYs�������o�d����IDATx^���W��}�}��s�{�s���g�t��epww��N ��I �  �@�@�]�'F���o���ݫv�������&lt;�g�k������Uk��k���P��+��eˢT�R��`��%J�p�¾��\��`pGƪ\k0\i��!%0���`�
1
  • Looks like an Encoding issue with the data from Ajax Response. Try parsing json and Try changing it to suitable format like Base64 etc. You can handle this from server side too. Commented Sep 14, 2014 at 16:16

2 Answers 2

3

In order to use <img src="data:image/PNG;base64' the base64 part is because you need to return a Base64 string instead of array of bytes therefore you need to convert your byte[] to 64Base using: Convert.ToBase64String(buffer)

So using your code as example:

ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_Obj.GetImage(), typeof(byte[]));

Your WebApi method should be returning:

return Convert.ToBase64String(resourceByteArray);
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not much into the asp and .NET but you should probably convert your binary array in text by using Convert.ToBase64String method, before putting it in response.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.