Reputation: 874
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.
Upvotes: 1
Views: 745
Reputation: 1493
@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.
Upvotes: 2
Reputation: 7294
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']) . '" />';
Upvotes: 2
Reputation: 22911
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']) . '" />';
}
Upvotes: 2