Search code examples
phpgetid3

Display image in browser with getID3


I want to create a php file that will return an image of an mp3 song when called as the src parameter in the img tag of html. Something like this:

<img src="/imageReturn.php?song=SongName">

In order to get the image from the mp3 file I used the getID3 library. My PHP code:

$song= $_GET["song"];
require_once("getID3-1.9.15/getid3/getid3.php");
$Path=$song.".mp3";

$getID3 = new getID3;
$OldThisFileInfo = $getID3->analyze($Path);
if(isset($OldThisFileInfo['comments']['picture'][0]))
{
    $ImageBase='data:'.$OldThisFileInfo['comments']['picture'][0]['image_mime'].';charset=utf-8;base64,'.base64_encode($OldThisFileInfo['comments']['picture'][0]['data']);
}

header('Content-Type: image/jpeg');
echo $ImageBase;

The problem is that I cant get php display the image. How to fix it?


Solution

  • You don't have to encode the image to base64, you can directly echo the image data.

    $getID3 = new getID3;
    $OldThisFileInfo = $getID3->analyze($Path);
    
    if (isset($OldThisFileInfo['comments']['picture'][0])) {
        header('Content-Type: ' . $OldThisFileInfo['comments']['picture'][0]['image_mime']);
        echo $OldThisFileInfo['comments']['picture'][0]['data'];
    }