tags:

views:

249

answers:

3

I have images stored in mysql as mediablobs, and I'd like to load (show) them directly from the database without having to save them as files first.

I need to load multiple images into a table (thumbs), so the header command won't do it. this is what I do:

     $imagePath = 'files' . DS . 'recipe_' . $recipe['Recipe']['id'] . '.tmp';
     file_put_contents($imagePath ,$recipe['Recipe']['image']);
  echo $html->image(DS . $imagePath);
+4  A: 

You create a script named getimage.php. The thumbs in the table should be something like this:

<img src='<path>/getimage.php?id=<image_id>' />

The scipt getimage.php does the database lookup and then outputs something like:

...
header('Content-Type: image/jpeg');
header('Content-Length: ' . strlen($recipe['Recipe']['image']) );
echo $recipe['Recipe']['image'];
...
Flavius Stef
@hinge: you just have to understand the getimage.php as your image resource wich you use in the src attribute and you got it (you can add nice things like authentication or hotlink-prevention there too)
ole_berlin
Thanks - seems right/should have thought of it. Ill try it out now...
A: 

The other option would be to use an apache redirect either in httpd.conf or a .htaccess file that redirects all image requests (.gif|.jpg|*.png|etc, etc) to your getImage.php script. Then getImage.php would pull from the database, send appropriate headers and output the binary data.

The advantage of this over Flavius Stef's answer is that then your tags could have a regular looking source (/path/to/image.jpg) rather than an obvious retrieval system. It would also clean up your apache access logs at the same time.

KOGI
A: 

I got it working....

This is what I put in the table:

'<img src= "/recipes/download/" . $recipe['Recipe']['id']) . '"/>'

and this is the download action:

function download($id) {
    Configure::write('debug', 0);
    $file = $this->Recipe->findById($id);

    header('Content-type: image/png' );
    header('Content-length: ' . strlen($file['Recipe']['thumb'])); // some people reported problems with this line (see the comments), commenting out this line helped in those cases
    header('Content-Disposition: attachment; filename="'.$file['Recipe']['thumb'].'"');
    echo $file['Recipe']['thumb'];

    exit();
}