akoimeexx icon

Abstract Data URI class

akoimeexx | PRO | 02/05/13 02:57:50 AM UTC | 0 ⭐ | 253 👁️ | Never ⏰ | []
PHP |

2.74 KB

|

None

|

0 👍

/

0 👎

<?php
    /**
     * (string) DataURI::Encode( (string) $file, (boolean) [$b64=true])
     *  Parameters
     *      (string) $file: path of file to be encoded
     *      (boolean) $b64: base64-encoding flag
     *  
     *  Returns a valid data uri (string) on success, (boolean) false 
     *  on failure.
     *  
     *  Example: <img src="<?= DataURI::Encode("image.png"); ?> />
     * 
     * 
     * (string) DataURI::Decode( (string) $datauri, (string) [$tmp_suffix='raw'])
     *  Parameters
     *      (string) $datauri: valid data uri to be decoded
     *      (string) $tmp_suffix: default fallback suffix if a 
     *           proper filename extension cannot be determined
     *  
     *  Returns the path and filename (string) of the decoded file on 
     *  success, (boolean) false on failure.
     *  
     *  Example: echo DataURI::Decode('data:plaintext/txt;charset=UTF-8;base64,My4xNDE1OTI2NQ==');
     *       // returns /tmp/plaintext-??????.txt, with contents of 
     *       // 3.14159265
     */
    abstract class DataURI {
        public static function Encode($file, $b64=true) {
            try {
                $mt = DataURI::get_mime_type($file);
                $data = file_get_contents($file);
                if($b64) {
                    $b64 = ';base64';
                    $data = base64_encode($data);
                }
                return sprintf("data:%s%s,%s", $mt, $b64, $data);
            } catch (Exception $e) {
                error_log($e->getMessage());
            }
            return false;
        }
        public static function Decode($datauri, $tmp_suffix = 'raw') {
            try {
                $metadata = explode(';', substr($datauri, 0, strpos($datauri, ',')));
                $data = substr($datauri, strpos($datauri, ',') + 1);
                if(array_search('base64', $metadata) !== false) { $data = base64_decode($data); }
                
                $tmp_prefix = 'data';
                if(($mimetype = substr($metadata[0], strpos($metadata[0], ':') + 1)) != '') {
                    $tmp_prefix = substr($mimetype, 0, strpos($mimetype, '/'));
                    $tmp_suffix = substr($mimetype, strrpos($mimetype, '/') + 1);
                }
                
                while (true) {
                    $tmp_filename = tempnam(sys_get_temp_dir(), "$tmp_prefix-") . ".$tmp_suffix";
                    if (!file_exists($tmp_filename)) break;
                }
                if(file_put_contents($tmp_filename, $data) !== false) {
                    return $tmp_filename;
                }
            } catch (Exception $e) {
                error_log($e->getMessage());
            }
            return false;
        }
        private static function get_mime_type($file, $def_mime_type = 'application/octet') {
            $mimetype = $def_mime_type;
            if(function_exists('finfo_file')) {
                // Use finfo_file to grab mimetype, if possible
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mimetype = finfo_file($finfo, $file);
                finfo_close($finfo);
            } elseif(function_exists('mime_content_type')) {
                // finfo_file is unavailable, attempt to use deprecated mime_content_type
                $mimetype = mime_content_type($file);
            }
            return $mimetype;
        }
    }
?>

Comments