从字节数组构造JPEG图像

I'm trying to construct a JPEG image from a byte string using PHP. I understand the base64 decode and encoding part, but right now part of my data looks like this:

FF D8 FF FE 0 24 65 0 EF 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 F0 0 40 1 B 0 32 12 B 51 4 51 4 0 0 FF DB 0 84 0 3 2 2 2 2 2 3 2 2 2 3 3 3 3 4 7 4 4 4 4 4 8 6 6 5 7 A 9 A A A 9 A 9 B C 10 D B C F C 9 A E 13 E F 10 11 12 12 12 B D 13 15 13 11 15 10 11 12 11 1 3 3 3 4 4 4 8 4 4 8 11 B 46 15 73 95 5C 12 7 5A E3 75 82 9A C3 67 D7 6A 90 8A 1B 78 A 88 5B 30 CE B8 F4 3F CC 36 54 E5 0 C5 AC AF D4 B0 2B 45 A3 D3 CA 29 8F 77 AD D6 C9 13 B3 A6 2F FC....

I know for a fact that it's a jpg coming from a arduino camera, sent using a POST request to my PHP script, and that FF D8 marks the start of a JPG but that's all I know.

My question is given this string, how to do convert it to base64 or a proper jpg image which I can upload using PHP?

edit: I tried decoding an actual jpg file using file_get_contents("temp.jpg") and I got this:

137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 200 0 0 0 200 8 6 0 0 0 173 88 174 158 0 0 32 0 73 68 65 84 120 94 237 157 7 92 20 199 23 199 127 32 216 197 130 40 216 187 216 131 93 99 47 81 35 118 141 189 197....

Close but not exactly the same format.

Thanks.

You have several options, although I cannot test them at the moment to see what may work.

  1. The hex2bin function is available in PHP ≥ 5.4.0 and converts hex to a binary string. Do note, however, that you'll probably have to remove the spaces from the string prior to converting.

  2. If you're running a lower PHP version, you can use pack('H*', $string) instead to achieve the same results. Again, no spaces.

  3. The binary string you obtain by using either of the above methods can be converted to base64 by using base64_encode.

  4. Finally, imagecreatefromstring should work on base64 data, if my memory serves me correctly.

No guarantee that any of these will work, since I can't check at the moment, but there are no other answers so hopefully it helps. Good luck!