简体   繁体   中英

Displaying PNG images from MySQL

I'm trying to display an image from a MySQL database and my code works fine if the image is a JPG, but if I modify the content-type to display a PNG, it doesn't work... How do I make it work for PNG??

<?php

    // configuration
    require("../includes/config.php"); 

    header('Content-type: image/JPG');
    $username = "xxxxx";
    $password = "*****";
    $host = "localhost";
    $database = "database";
    @mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
    @mysql_select_db($database) or die("Can not select the database: ".mysql_error());
    $query = mysql_query("SELECT * FROM images");

    while($row = mysql_fetch_array($query))
    {
        echo $row['image'];
    }
?>

Also, is it possible to display the image along with its name and description? Thanks!

If you don't mind not supporting older browsers, you can use data urls to display your images and a description http://en.wikipedia.org/wiki/Data_URI_scheme .

<figure>
  <img src="data:image/png;base64,<?php echo base64_encode($row['image']); ?>" alt="Your alternative text" />
  <figcaption>Some more description</figcaption>
</figure>

Saving images in a database is not very useful in almost all cases. You should be carefull with upper and lower letters in the mimetype, see http://de.selfhtml.org/diverses/mimetypen.htm (it's german, but you will be able to read the list). And as a last advice - look at the mysqli_* functions http://www.php.net/manual/en/book.mysqli.php .

// Edit: Just an idea, but if you have multiple images in the database your image might be broken, because you just put them all into one image. This will not work! With your code, you can only display one image at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM