Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Extracting album art/album cover image from a mp3 file using getID3 in Cake PHP?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.57k
    Comment on it

    In the previous blog Extracting metadata info from a mp3 file using getID3 in Cake PHP? i explained how to extract information regarding a mp3 file using getID3. In this blog i will explain how to extract the image (if its there) inside a mp3 file using getID3.

    The rest of the code is same as in the previous blog which is:

        <?php 
            public function extractFile($filename) {
                App::import('Vendor', 'getID3', array('file'=>'getid3/getid3.php'));
                $this->getID3 = new getID3;
                // Analyze file and store returned data in $ThisFileInfo
                $ThisFileInfo = $this->getID3->analyze($filename);        
                return $ThisFileInfo;
            }
        ?>
        <?php
             public function index() {
                $this->layout=null;
                $arr = array();
                $dir = new Folder(WWW_ROOT . 'audio');
                $files = $dir->find('.*\.mp3', true);
                $result = $this->extractFile(WWW_ROOT . "audio/Khaab.mp3");
                $tmp = $this->checkVal($result['tags'],"Khaab.mp3");
                $arr[] = array(
                            "Song_name" => $value,
                            "album"=>$tmp["album"][0],
                            "artist"=>$tmp["artist"][0],
                            "title"=>$tmp["title"][0],
                            "year"=>$tmp["year"][0],
                            "genre"=>$tmp["genre"][0]
                        );
                print_r($arr);
            }
        ?>

    After extracting file info in the next phase i have called ajax function which send a request to PHP page and return data which is in format of string.

    Here is the AJAX call:

    $.ajax({
    	url: "users/getImage/",
    	type: 'POST',
    	success: function(data) { 
    		if (!isEmpty(data)) 
    			$(".pic img").attr("src",data);
    		else{
    			$(".pic img").attr('src', '/mediaPlayer/img/player-bg.jpg');
    		}
    	},
    	error: function(xhr, textStatus, errorThrown) {
    		alert("An error occurred with the server" + xhr);
    	}
    });

    Here is the getImage() function in controller:

    <?php
        public function getImage(){
        	$this->layout = null;
        	$picture = $this->extractFile(WWW_ROOT . "audio/Khaab.mp3");
    		if(isset($picture['id3v2']['APIC']) && !empty($picture['id3v2']['APIC'])){
    			$cover='data:'.$picture['id3v2']['APIC'][0]['image_mime'].';charset=utf-8;base64,'.base64_encode($picture['id3v2']['APIC'][0]['data']);
    		}
    		elseif(isset($picture['comments']['picture'][0]['data']) && !empty($picture['comments']['picture'][0]['data'])) {
    			$cover='data:'.$picture['id3v2']['APIC'][0]['image_mime'].';charset=utf-8;base64,'.base64_encode($picture['id3v2']['APIC'][0]['data']);
    		} else {
    			$cover = null;
    		}
    		if (isset($picture['id3v2']['APIC'][0]['image_mime']) && !empty($picture['id3v2']['APIC'][0]['image_mime'])) {
    			$mimetype = $picture['id3v2']['APIC'][0]['image_mime'];
    		} else {
    			$mimetype = 'image/jpeg'; // or null; depends on your needs
    		}
    		if (!is_null($cover)) {
    			// Send file
    			header("Content-Type: " . $mimetype);
    
    			if (isset($picture['id3v2']['APIC'][0]['image_bytes']) && !empty($picture['id3v2']['APIC'][0]['image_bytes'])) {
    				header("Content-Length: " . $picture['id3v2']['APIC'][0]['image_bytes']);
    			}
        		echo @$cover;
    		}
    	}
    ?>

    In the controller i have a function named getImage() by default i have provided a mp3 file. The function extract the meta-data of the file just like in previous example. But here i have used only necessary part of the array which contains the image.

    After extraction the array i have checked whether the array contains the image or not. If its contains the image then i have converted the image into base64 format using base64_encode() and then embed the image data directly into the document with data URIs which is readable by the html. The syntax of data URIs is:

    data:[<mime type>][;charset=<charset>][;base64],<encoded data>

    An example here https://css-tricks.com/examples/DataURIs/

    The result is then echoed back as a string to the html page and in ajax success. Inside success function body I have changed the src of the <img> to the response received from the server. If the response is not empty then i have changed src to data received else i have provided a default image.

    success: function(data) { 
    		if (!isEmpty(data)) 
    			$(".pic img").attr("src",data);
    		else{
    			$(".pic img").attr('src', '/mediaPlayer/img/player-bg.jpg');
    		}
    	},

    This is the HTML code after the ajax call has been made:

    <div class="pic">
        <img src="data:image/jpeg;charset=utf-8;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7">
    </div>

    Though i have changed the lengthy <encoded data>.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: