Home > Blockchain >  How do I set data:image/ filetype dynamically?
How do I set data:image/ filetype dynamically?

Time:11-19

I have a database which contains images saved as BLOBs. I can successfully use the image on a page like so :

<img src="<?php echo 'data:image/jpeg;base64,'.base64_encode($image)?>" alt="Landing" width="150px">

However this requires setting the file extension manually in the actual statement at data:image/jpeg;. The problem is that I have lots of various images in various formats. I want to make sure that the filetype is set properly based on the actual file extension of the specific file for each image. I already have a nested array which contains all the file extensions for those files.

Nonetheless I am having trouble setting the extension dynamically. I've tried simply replacing the '' single quotes with "" to allow me to easily use a variable inside of the statement like so :

<img src="<?php echo "data:image/$images['monitor']['extension'];base64,".base64_encode($image)?>" alt="Landing" width="150px">

This doesn't work because the src tag itself contains double-quotes already I believe. My IDE tells me an error Cannot use '[]' for reading. I've also tried using concatinated single quotes instead :

<img src="<?php echo 'data:image/' . $images['monitor']['extension'] . ';base64,'.base64_encode($image)?>" alt="Monitor" width="150px">

Which also did not work. I was unable to find any solution to this online myself. Is there any way to dynamically set the file extension? Although setting jpeg for each image mostly works for instance doing so for the image/x-ico tab icon renders the image unable to load properly.

CodePudding user response:

Assuming that the BLOB contains the actual binary data of the image.

Just make sure that the extensions match with the required syntax

jpg file : <img src="data:image/jpeg;base64,[base64_encoded_data]

png file : <img src="data:image/png;base64,[base64_encoded_data]

ico file : <img src="data:image/icon;base64,[base64_encoded_data]

So a sample example is like the following:

<?php
$image=file_get_contents("http://www.createchhk.com/SO/sample1.png");

$file_ext = 'png';
?>

Test for PNG<br>
<img src="data:image/<?php echo $file_ext; ?>;base64,<?php echo base64_encode($image)?>" alt="Landing" width="50px"><br>


<?php
$image2=file_get_contents("http://www.createchhk.com/SO/sample1.jpg");
$file_ext2 = 'jpeg';
?>


Test for JPG<br>
<img src="data:image/<?php echo $file_ext2; ?>;base64,<?php echo base64_encode($image2)?>" alt="Landing2" width="50px"><br>

<?php
$image3=file_get_contents("http://www.createchhk.com/SO/sample1.ico");
$file_ext3 = 'icon';
?>


Test for JPG<br>
<img src="data:image/<?php echo $file_ext3; ?>;base64,<?php echo base64_encode($image3)?>" alt="Landing3" width="50px"><br>

The result can be seen here:

http://www.createchhk.com/SO/testSO_18Nov2021.php

  • Related