简体   繁体   中英

Display images with different extension (PHP)

Below are coding that I currently use to display images from database :

$con = mysqli_connect('localhost','root','','demo') or die('Unable To connect');
$query = mysqli_query($con,"SELECT * FROM images");
while($row=mysqli_fetch_assoc($query))
{
    echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
}

Problem with those coding : It only display images with .png extension because I am using echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />'; to display it.

What I am trying to do : I wanted to display images with extension .jpeg .png and .gif as well.

Is there anybody that can help me with other simple way of displaying images? Thank you.

Store the format in the database as well:

$con = mysqli_connect('localhost','root','','demo') or die('Unable To connect');
$query = mysqli_query($con,"SELECT * FROM images");
while($row=mysqli_fetch_assoc($query))
{
    echo '<img src="data:image/' . $row['format'] . ';base64,' . base64_encode($row['image']) . '" />';
}

Hi Just get the image extension and use it

$ext = pathinfo($row['image'], PATHINFO_EXTENSION);
echo '<img src="data:image/' . $ext . ';base64,' . base64_encode($row['image']) . '" />';

@FrankerZ already gave correct solution but if you have already stored base64 images on your database it will be problematic to add format column.

You can discover the mime type of image from base64 like that;

$img = $row['image']; // base64 of your image 
$fileInfo = finfo_open(); // file info resource 
$mimeType = finfo_buffer($fileInfo, $img, FILEINFO_MIME_TYPE);

If you have already existing records, do not apply this methodology on your each iteration . Simply add new column to your database, and fill/update these new colums using this methodology. After that, use @FrankerZ 's solution.

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