3

I've to make POST request to an API and this API returns an image which I want to show on canvas or img element. The problem is weird characters are coming in response but in network tab, image is shown properly(screenshots below) ImageResponse_weird

Preview_network_tab

I've tried everything mentioned in AJAX - Weird characters in img tag after request response

I've tried to convert to base64, load using new Image(), tried to convert to blob, load using FileReader(), but blank image is loaded. blank_image

Instead of POST request, if I use some static image URL with new Image() or FileReader(), it works without issues. How do I render an image that comes as a response from POST request? Any help is appreciated.

  • It’s advised to save the image somewhere and simply send the link to that image in your http response like you tried with the static url. If there are no other options try to base64 encode the image from the source and send the base64 encoded image which you should be able to decpde on the client side. – Quinten Dec 19 '18 at 18:50
  • What is the type of response you are fetching? I guess it might be because of character encoding. – MJN Dec 19 '18 at 18:50
  • @Quinten, static url is not an option, the api generates image based on the payload. If the api response itself is base64, it can be rendered is what you're suggesting ? @Manjunath, Response is an image, `Content-Type: image/jpeg` in response headers. Any idea what type of format those weird characters represent? – lifetimeLearner007 Dec 20 '18 at 05:14
  • If the api response is base64 encoded you could decode it, save it and do anything you like or you could put it directly in an img’s src tag as it automatically decodes itself (if that is your goal) – Quinten Dec 20 '18 at 20:51
  • i had same issue and solved it here : https://stackoverflow.com/questions/70534780/convert-weird-image-characters-for-use-in-image-src – Marzieh Mousavi Dec 31 '21 at 10:13

1 Answers1

1

The answer provided by fotinakis in How to parse into base64 string the binary image from response? worked.

While making POST request itself, the responseType has to be set to arraybuffer which can later be converted to base64. Getting base64 from binary was the issue. The success callback of ajax returns binary by default unless set otherwise.

Other responseTypes can be found in https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType.

I still don't understand one thing though. Static image URL(GET) also returns binary data which gives no issues with new Image() but if I pass the same binary data from POST request success callback, it doesn't work.