5

I tried to link stored image(blob data) inside MySQL DB to PHP but only thing I achieved was whole page of characters. This is what I did:

$query = "SELECT image FROM uploads WHERE id = {$id}";
$image_array = mysql_query($query, $connection);
$row = mysql_fetch_array($image_array);
$image = $row['image'];

echo $image;
// echo base64_decode($content);

This displays raw data how it is stored. I would like to link it into HTML tag or atleast display it on page, where I display a lot another stuff to so header('Content-type: image/png'); is not solution for me.

Any advice?

Robert
  • 65
  • 2
  • 5
  • You can find your exact SO answer [here](http://stackoverflow.com/questions/13225726/i-need-my-php-page-to-show-my-blob-image-from-mysql-database) – Smile Jun 07 '13 at 13:23

3 Answers3

8

To show the image correctly you just need to put one header with Content-type: image/png before echo

header("Content-type: image/png");
echo (base64_decode($row['image']));

If you want to place instead in an image tag you just need to use this code

echo '<img src="data:image/png;base64,' . $row['image'] . '" />'; 
Fabio
  • 23,183
  • 12
  • 55
  • 64
1

You need to give proper headers, otherwise the page wont know what you're sending it.

// define results into variables 
$name=mysql_result($result,0,"file_name"); 
$size=mysql_result($result,0,"file_size"); 
$type=mysql_result($result,0,"file_type"); 
$content=mysql_result($result,0,"file_stream"); 

// give our picture the proper headers...otherwise our page will be confused 
header("Content-Disposition: attachment; filename=$name"); 
header("Content-length: $size"); 
header("Content-type: $type"); 
echo $content; 
Pedro Estrada
  • 2,384
  • 2
  • 16
  • 24
0

You should use something that is called 'Inline image'. Use this code to display the image on a page, asssuming the $image variable contains base64 encoded data:

<img src="data:image/png;base64,<?php echo $image; ?>" alt="Larry" />

Source: https://en.wikipedia.org/wiki/Data_URI_scheme

Stan
  • 493
  • 4
  • 15