convert binary data to image using php

Kartik it picture Kartik it · Jul 11, 2013 · Viewed 19.2k times · Source

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

Answer

Baba picture Baba · Jul 11, 2013

The data you are trying to retrieve has HTML and its in HEX format but the image is corrupt or not valid.

To get the data:

// $url = "log.txt";
$url = "http://freezinfo.com/gg.php";

// Load Data from URL
$data = file_get_contents($url);
// Remove ALL HTML Tags
$data = strip_tags($data);

The Errors

Now Lets Examine the Header

 echo substr($data, 0, 4); // returns FF00

FF00 is not a valid jpeg prefix It should start with FFD8 OR FfD9

How did i know its a JPEG file and its not valid ?

 echo pack("H*", substr($data, 0, 60));

Output

����JFIF

It clearly has reference to JFIF which is JPEG File Interchange Format

How can it be fixed ?

A quick Image validation imagecreatefromstring

$data = pack("H*", $data); // Convert from hex
$im = @imagecreatefromstring($data);
var_dump($im); // returns false 

Looking at the image header again $data .. i could see a pattern

FF00D800FF00E000000010004A00460049
  ^^  ^^  ^^  ^^  ^^  ^^  ^^  ^^

I noticed that 00 is been inserted so remove that would actually give us a valid image header FFD8

You can fix this with a simple loop

// Trim all Spaces
$data = trim($data);

$newData = "";
for($i = 0; $i < strlen($data); $i += 4) {
    $newData .= $data{$i} . $data{$i + 1};
}

$newData = pack("H*", $newData);
$im = imagecreatefromstring($newData);
var_dump($im); // resource(6, gd)

Output

resource(6, gd)

Conclusion

You really need to examine the way you are converting your image to hex , it looks messed up form here