Converting array bit into actual image

Viewed 83

I have an array bit like this:

[255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 255, 219, 0, 67, 0, 1, 1, ...]

And I need to convert this into an actual image.

So I followed this python script that does the same and works properly:

file = x['data']['file']['file'] 

listRes = file.replace(' ', '')
listRes = listRes.replace('[', '').replace(']', '')
listRes = listRes.split(',')
for i in range(len(listRes)):
    listRes[i] = int(listRes[i])
f = open('x.png', 'wb')
f.write(bytes(listRes))
f.close()

And this is my similar php code:

if(!empty($que["answer"]["file"])){
    $strbit = str_replace("[","",$que["answer"]["file"]["file"]);
    $strbit = str_replace("]","",$strbit);
    $strbit = str_replace(" ","",$strbit);
    $arrbit = explode(',', $strbit);
    for($j=0;$j<count($arrbit);$j++){
        $arrbit[$j] = (int)($arrbit[$j]);
    }
    $imageName = str_random(10).'.'.'png';
    \File::put(storage_path(). '/images/' . $imageName, ($arrbit));
}

But now the problem is that the exported image looks like this:

capture

Now instead of \File::put(storage_path()... I tried using file_put_contents($imageName, pack("C*", ...$arrbit)); but it does not export anything at all!

So what's going wrong here? How can I solve this issue?


UPDATE #1:

I tried this:

if(!empty($que["answer"]["file"])){
        $strbit = str_replace("[","",$que["answer"]["file"]["file"]);
        $strbit = str_replace("]","",$strbit);
        $strbit = str_replace(" ","",$strbit);
        $arrbit = explode(',', $strbit);
        for($j=0;$j<count($arrbit);$j++){
            $arrbit[$j] = (int)($arrbit[$j]);
        }
        $imageName = str_random(10).'.'.'jpeg';
        file_put_contents($imageName, pack("C*", ...$arrbit));
    }

But does not export any image and also not return any error!

1 Answers

So, main issue was: how to convert input format -- string of comma separated character codes in brackets -- into binary form and write it to the file.

PHP has pack() function which fits this purpose nicely. Specifically, we need C* format as we are going to output raw 8-bit characters. So, given we have this input:

$arr = [255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 255, 219, 0, 67, 0, 1, 1, /* ... */];

This is how we can convert it into a binary string (note the ... token -- it is very important here, as pack() expects one argument per character converted, not an array as a single argument):

$str = pack("C*", ...$arr);

Finally, original question was asking about .png files, but apparently the example data has JFIF header, which indicates .jpg format. If format is not known, one can use getimagesize() to guess it (note: the function requires file already written to disk, not a binary string with file contents).

Related