I have binary image data saved in my old database, it is saved by my old developer, now i want to display image from that using PHP, but I can not.
I have tried imagecreatefromstring
but it returns FALSE
.
Binary example data: http://freezinfo.com/gg.php
Given the string displayed as text (extactly this sequence), it's a lineup of hexadecimal numbers.
In Jpeg, the magic numbers of such a file are FF D8
as the first two bytes and FF D9
as the last two bytes (compare with How to identify contents of a byte[] is a jpeg?).
These hexadecimal (hex in short) numbers can be found at the beginning and end of your sequence as well:
FF00D800FF00 ... 1F00FF00D9000
## ## ## ##
Looking for these magic numbers also reveals that the hex values are append with 00
always. It also shows that at the very end an extra single 0
is found.
So four characters always form one value. Hex-encoded this looks like 16 bit values however the value never goes over the 8 bit range (0-255), therefore there is always 00
visible.
With this information alone one then can try to turn this into a binary string that PHP's imagecreatefromstring
can deal with:
$string = implode('', // map array of binary strings to binary string
array_map('chr', // map ord integer value to character
unpack('v*', // unsigned short (always 16 bit, little endian byte order)
pack("H*", $data) // hex to binary (high nibble first)
)));
Using such a string then in
$result = imagecreatefromstring($string);
imagejpeg($result, 'test.jpg');
reveals the following PHP error notice:
imagecreatefromstring(): gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: bad Huffman code
and the following image:
This looks desperately broken. So you are probably facing an additional encoding problem here. The last NUL
byte suggests that more has been done and there also must be a reason why the data has been stored as 16 bit hex values instead of just binary data (blob) as databases have support for that.
But don't waste too much time, because of the flaw in the software and configuration that was used in the past, this might just be data-loss so all you can do is to restore from backups.