views:

228

answers:

2

I have some pretty simple php code that returns binary image data from a database.

ob_start();

$stmt = $db->prepare($sql);
$stmt->execute(array($ImageID));
$stmt->bindColumn(1, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

ob_clean();
header("Content-Type: " . $content_type);

fpassthru($lob);

Let's call this script get_image.php. I'm calling this script from another one to get the image data and then process it. LIke so.

$src = file_get_contents('example.com/get_image.php?ImageID=foo');

$src = imagecreatefromstring($src);
imagecopyresized($newfile, $src, 0, 0, 0, 0, $newwidth, $newheight, $origwidth, $origheight);

I'm getting errors from the image processing functions saying the "Data is not in a recognized format". After taking a look at the response it looks like my $src variable includes the headers as well as the binary data. I've been doing research but I can't figure out how to get rid of the header output and just work with the raw binary string. Any help is appreciated.

To be clear, if I print out the $src string, instead of raw binary data I get the following.

HTTP/1.1 200 OK
Date: Thu, 19 Nov 2009 17:33:01 GMT
Server: Apache/2.2.8 (Unix) ...
X-Powered-By: PHP/5.2.11
Connection: close
Content-Type: image/jpeg

/* Then all the binary data */
+1  A: 

I'm no PHP expert, which is probably where the real solution is (get the response body only, no headers) but I do know my HTTP. To that end, the headers and body of an HTTP request like you have above is always delimited by two <CR><LF>'s. You should be able to take the response, and get a sub-string from there. Example iDontKnowPhp code:

$start = $src.positionOf('<CR><LF><CR><LF>')
$stop  = $src.lenght()
$img   = $src.sub($start, $stop)
Stu Thompson
Thanks. This was the easy solution and it works well. I added a check for headers first. stripos($src, 'http') === 0
Marco
+1  A: 

It looks like the PHP fopen stream wrapper isn't stripping the header. Instead of file_get_contents try CURL instead:

<?php

$ch = curl_init("http://www.example.com/myimagescript.php");

curl_setopt($ch, CURLOPT_HEADER, 0);  // No headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   // grab the content of the file
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

$contents= curl_exec($ch);
curl_close($ch);


?>
pygorex1