user2026794
user2026794

Reputation: 123

Error displaying blob image in php/html

I am trying to display image from a blob field of a MySQL table. Looks like I have some sort of error in the following line. As soon as I put "header("Content-type: image/jpeg")" things get messed up and instead of displaying webpage, all source code of the page is displayed.

Please let me know how to correct.

<div class="image" align="left">
    <a href="<?php header("Content-type: image/jpeg"); echo $rec['image']; ?>">
        <img src="<?php echo $rec['image']; ?>" width="150" border="0"/>
    </a>
</div><!-- image --> 

Upvotes: 0

Views: 2018

Answers (3)

Shady Manaa
Shady Manaa

Reputation: 44

I've done something like that retrieving blob from my database in another way that you may find useful, here is the code example.. see if it suits your needs and if you needed anymore help let me know.

while ($row = mysql_fetch_array($hc_query2)) {
                        $title = $row['title'];
                        $text = $row['text'];
                        $image = $row ['image'];
                        $output ='<div class="HCInstance"><img src="data:image/jpeg;base64,' . base64_encode($image) . '" alt="High Council" width="100px" height="100px"/>
                        <div class="HCHeader"><h2>'.$title.'</h2></div><br/><div class="HCDetails"><p>'.$text.'</p></div></div>';
                        echo $output;
                    }

Upvotes: 0

itsmejodie
itsmejodie

Reputation: 4228

You're trying to put the image data inline inside the content. The only feasible way to do this is via a Data URI data URI. Something like:

<img src="data:image/jpeg;base64,<?= base64_encode($rec['image']) ?>" width="150" border="0" />

However, what you probably want to do is put it into a separate script. So your HTML would be:

<a href="showimage.php?id=XXX"><img src="showimage.php?id=XXX" width="150" border="0" /></a>

And your showimage.php script would be:

<?php
// Get $rec from database based on the $_GET['id']
header('Content-Type: image/jpeg');
echo $rec['image'];
?>

Upvotes: 0

jcsanyi
jcsanyi

Reputation: 8174

You normally don't put the actual image contents in the src= attribute of the image tag. Instead, you point to the URL of an image file.

(There are ways to include the image source directly in the HTML, but it doesn't work consistantly with all browsers, and you still won't have your <a> link working properly.

Instead, the best way to do this is to create a separate PHP file to serve the image.

Your HTML:

<div class="image" align="left">
<a href="myimage.php?key=<?php echo($key) ?>"><img src="myimage.php?key=<?php echo($key) ?>" width="150" border="0"/></a>
</div><!-- image -->

myimage.php:

<?php
    header("Content-type: image/jpeg");
    $key = $_GET['key'];
    // todo: load image for $key from database
    echo $rec['image'];

Upvotes: 1

Related Questions