0

I don't know if I missed something but I can't receive an image (binary) in javascript. I can do the same in iPhone and Android(with another cose, of course), but not if I'm using javascript.

SCENARIO:

Server Side

I have a server where the image is stored.

Code: (test1.php)

$image_url = 'http://weburbanist.com/wp-content/uploads/2011/11/lorem-ipsum.jpg';


$bin = file_get_contents($image_url);

echo $bin;

Client Side (Javascript)

I ask to the server, via URL GET/POST, the image, but I can't receive it in Javascript using AJAX request. I want to store it in a .

Code:

var activeXhr = new XMLHttpRequest();

activeXhr.open('GET', 'test1.php', true);

activeXhr.onreadystatechange = function()
{
    if(activeXhr.readyState == 4){
       var bin_img = activeXhr.responseText;
       var dataURL="data:image/jpeg;base64,"+bin_img;

       $('#test_img').attr('src',dataURL);
    }
};
activeXhr.send(null);

PROBLEMS:

I can't convert this data received in BASE64 or using btoa (returns empty)

QUESTION:

How I can receive an raw image in JAVASCRIPT?

Kotik_o
  • 295
  • 6
  • 19
  • 1
    Possible duplicate of [How to display binary data as image - extjs 4](http://stackoverflow.com/questions/14915058/how-to-display-binary-data-as-image-extjs-4) – machineghost Dec 30 '16 at 18:50
  • 1
    I *strongly* encourage everyone to use Stack Overflow to get help, but before you do it's nice to perform some "due diligence" with a basic Google search. If you search for just `javascript binary image` in Google your very first result will be an existing SO post which answers your question. – machineghost Dec 30 '16 at 18:52
  • why not just do ` – Heretic Monkey Dec 30 '16 at 18:59
  • I know nothing about php, but it seems there are methods specifically made for handling images being sent to the browser: http://php.net/manual/en/function.imagecreatefromjpeg.php, http://php.net/manual/en/function.imagejpeg.php – Heretic Monkey Dec 30 '16 at 19:36

1 Answers1

0

As you do already use jQuery, why not using its Ajax features for requests?

This is also much shorter:

$.get('test1.php').done(function (r) {
  // r is your raw image data;
});

Also would it be appropriate to set 'Content-Type' header in php:

<?php 

$image_url = 'http://weburbanist.com/wp-content/uploads/2011/11/lorem-ipsum.jpg';

$bin = file_get_contents($image_url);

header('Content-Type: image/jpeg');

die($bin); // use die/exit for safer output

Did you consider serving Base64 data from php like this:

die(base64_encode( $bin ));
CodeXP
  • 153
  • 1
  • 10