Your IP : 216.73.216.79


Current Path : /var/www/html/dosmv2/common/components/
Upload File :
Current File : /var/www/html/dosmv2/common/components/HelpersFunctions.php

<?php
namespace common\components;

class HelpersFunctions
{

    /**
     * Compress image and save
     *
     * @param String $source_url
     * @param String $destination_url
     * @param int $quality
     * @return void
     */
    public static function compressImage($sourceUrl, $destUrl, $fileName, $quality, $pngquality=null)
    {
        $info = getimagesize($sourceUrl);

        if ($info['mime'] == 'image/jpeg'){
            $image = imagecreatefromjpeg($sourceUrl);
        } elseif ($info['mime'] == 'image/gif') {
            $image = imagecreatefromgif($sourceUrl);
        } elseif ($info['mime'] == 'image/png') {
            $image = imagecreatefrompng($sourceUrl);
            imagealphablending($image, false);
            imagesavealpha($image, true);
        }
        
        //if directory not exist create it
        self::makedirs($destUrl);
        
        $fullpath = $destUrl . DIRECTORY_SEPARATOR . $fileName;
        
        if(!$quality) {
            imagepng($image, $fullpath, $pngquality);
        } else {
            imagejpeg($image, $fullpath, $quality);
        }
        
        
        return $fullpath;
    }
    
    /**
     * Create a directory if not exist
     */
    public static function makedirs($path, $mode=0777) {
        return is_dir($path) || mkdir($path, $mode, true);
    }
    
    /**
     * Convert base64 to image
     * @param string $base64_string with data meta
     * @param string $output_file
     * @return string output file name
     */
    public static function base64ToImage($base64, $destUrl, $fileName) {
        
        //if directory not exist create it
        self::makedirs($destUrl);
        
        $fullpath = $destUrl . DIRECTORY_SEPARATOR . $fileName;
        
        // open the output file for writing
        $ifp = fopen( $fullpath, 'wb' );
        
        // split the string on commas
        // $data[ 0 ] == "data:image/png;base64"
        // $data[ 1 ] == <actual base64 string>
        $data = explode( ',', $base64 );
        
        // we could add validation here with ensuring count( $data ) > 1
        
        if(count($data) > 1) {
            fwrite( $ifp, base64_decode( $data[ 1 ] ) );
        } else {
            throw new \Exception('Incomplete base 64 with data meta');
        }
        
        // clean up the file resource
        fclose( $ifp );
        
        return $fullpath;
    }
}