2

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 ...

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this code but image is not generate instead its generates the output like this,����JFIFHH��Photoshop 3.08BIM�HH8BIM� 8BIM�H/fflff/ff���2Z5-8BIM�p���
2

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);

2 Comments

when i run this it shows "Call to undefined function tmpnam()"
@GokulBasnet Yea, the function is called tempnam, that was a typo. I'll correct it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.