Gokul Basnet
Gokul Basnet

Reputation: 78

How to convert byte array to image in php?

I want to convert the byte array from a webservice to image. The webservice response array looks like the following but I could not figure out how to render this array back to an image. Please help me

'MemberImage' => 
    array (size=151745)
      0 => int 255
      1 => int 216
      2 => int 255
      3 => int 224
      4 => int 0
      5 => int 16
      6 => int 74
      7 => int 70
      8 => int 73
      9 => int 70
      10 => int 0
      11 => int 1
      12 => int 1
      13 => int 1
      14 => int 0
      15 => int 72
      16 => int 0
      17 => int 72
      18 => int 0
      19 => int 0
      20 => int 255 ...

Upvotes: 2

Views: 4978

Answers (2)

Sherif
Sherif

Reputation: 11942

If you want to convert that array to an actual byte array (i.e. a binary string in PHP) you could use the following function...

function arrayToBinaryString(Array $arr) {
    $str = "";
    foreach($arr as $elm) {
        $str .= chr((int) $elm);
    }
    return $str;
}

You could also use pack instead of the above function to do the same thing like so...

call_user_func_array('pack', array_merge(['C*'], $arr));

or in PHP 5.6+

pack('C*', ...$arr);

With that you could then - in theory - use the binary string as an image. So, for example, assuming you want to output the raw image data, and that the image is say a PNG, you would do something like the following, in conjunction with the above code...

header('Content-type: image/png');
echo arrayToBinaryString($myArray);

Just be sure to edit the Content-type header with whatever type the actual image is. If you don't know you could use something like getimagesize on the binary string to extract the MIME type from the image data.

$tmpFile = tempnam("/tmp");
$image = arrayToBinaryString($myArray);
file_put_conetnts($tmpFile, $image);
$imageData = getimagesize($tmpFile);
header("Content-type: {$imageData['mime']}");
echo $image;
unlink($tmpFile);

Upvotes: 2

Federkun
Federkun

Reputation: 36999

Use pack to convert data into binary string, es:

$data = implode('', array_map(function($e) {
    return pack("C*", $e);
}, $MemberImage));

// header here
// ...

// body
echo $data;

Upvotes: 2

Related Questions