Your IP : 216.73.216.240


Current Path : /home/juvelize/saulnois/tmp/install_695d2cf0b4957/src/
Upload File :
Current File : /home/juvelize/saulnois/tmp/install_695d2cf0b4957/src/TImg.php

<?php
/*
* @package		Tech Fry Library
* @license		https://www.gnu.org/licenses/gpl-3.0.en.html
*/

namespace TechFry\Library;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Image\Image;
use Joomla\CMS\Filter\OutputFilter;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Filesystem\Folder;
use Joomla\CMS\HTML\HTMLHelper;

class TImg
{
    // get_img(), resize_image(), reset_image(), create_image(), filter_image(), convert_image_to_webp()
    // copy_image(), delete_image(), load_image(), save_image(), get_images(), create_folder()
    // get_image_properties(), get_thumbnail()
    
    public $image;
  
  	public $text;
    
    public $image_filters = array(
        'GRAYSCALE' => IMG_FILTER_GRAYSCALE,
        'NEGATE' => IMG_FILTER_NEGATE,
        'BRIGHTNESS' => IMG_FILTER_BRIGHTNESS,
        'CONTRAST' => IMG_FILTER_CONTRAST,
        'COLORIZE' => IMG_FILTER_COLORIZE,
        'EDGEDETECT' => IMG_FILTER_EDGEDETECT,
        'EMBOSS' => IMG_FILTER_EMBOSS,
        'GAUSSIAN_BLUR' => IMG_FILTER_GAUSSIAN_BLUR,
        'SELECTIVE_BLUR' => IMG_FILTER_SELECTIVE_BLUR,
        'MEAN_REMOVAL' => IMG_FILTER_MEAN_REMOVAL,
        'SMOOTH' => IMG_FILTER_SMOOTH,
        'PIXELATE' => IMG_FILTER_PIXELATE,
        'SCATTER' => IMG_FILTER_SCATTER,
    );
    
    // 01. Save image from url to path
	public function get_img($url, $path)
	{
	    $fp = fopen($path, 'wb');
	    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
 	    curl_setopt($ch, CURLOPT_HEADER, 0);
 	    
 	    $data = curl_exec($ch);
 	    
        curl_close($ch);
    	
    	fclose($fp);
    	
    	return $data;
    }
    
    // 02. Resize image to new width
    public function resize_image($path, $width, $total = 0)
    {
        $size = getimagesize($path);
        
        if ($total)
        {
            $r1 = ($size[0])/($size[1]); // Width to Height Ratio
        
            // Calculate desired ratio
            $r2 = ($width * $width)/$total;
            if ($r1 < $r2)
            {
                $new_width = $width;
            }
            else
            {
                $new_width = ceil(sqrt($total * $r1));
            }
        }
        else
        {
            $new_width = $width;
        }
        
        // Load image file
        $image = $this->load_image($path);
        
        // Use imagescale() function to scale the image
        $new_image = imagescale($image, $new_width);

        // Save image
        $this->save_image($new_image, $path);
        
        return $new_width;
    }
    
    // 03. Returns random image from folder
    public function reset_image($folder = 'images')
    {
        $images = $this->get_images($folder);
        
        $i = count($images);
	    $random = mt_rand(0, $i - 1);
	
	    $image = $images[$random];
	    
	    $image_url = $folder . '/' . $image;
    
        return $image_url;
    }
    
    // 04. Create image
    public function create_image($options = [])
    {
        // $options array - width, height, bg_color, text_color, src_folder, pct, dst_folder, font_url/font_type
        // name, text, remove_words, file_name
        
        $title = $options['name'] ?? 'Sample Image';

        $image_name = OutputFilter::stringURLSafe($title);
        
        $width = $options['width'] ?? 600;
        $height = $options['height'] ?? 315;
        
        // A. Create blank image canvas
        $this->create_blank_image($width, $height);
        
        // B. Background color
        $bg_color = $options['bg_color'] ?? '#dddddd';
        $this->image_fill($bg_color);
        
        // C. Add random image to canvas
        if (isset($options['src_folder']) && !empty($options['src_folder']))
        {
            $random_image = $this->reset_image($options['src_folder']);
            
            $pct = $options['pct'] ?? 100; // 100 is original and 0 is transparent (bg color)
            $this->copy_image(JPATH_ROOT . '/' . $random_image, $width, $height, $pct);
        }
        
        // D. Add text to image
        if (isset($options['text']) && $options['text'])
        {
            $text = $options['text'];
            
            // Delete some words
            if (isset($options['remove_words']) && !empty($options['remove_words']))
            {
                $remove_words = explode(',', $options['remove_words']);
                foreach ($remove_words as $word)
                {
                    $text = str_ireplace(trim($word), '', $text);
                }
                $text = trim($text);
            }
            $this->text = $text;
            
            // Either font url or use font type
            $font_url = isset($options['font_url']) && $options['font_url'] ? $options['font_url'] : '';
            if ($font_url)
            {
                $font = $options['font_url'];
            }
            else
            {
                $font = 'media/com_tftools/fonts/' . $options['font_type'];
            }
            $font = JPATH_ROOT . '/' . $font . '.ttf';
          
          	$font_size = $this->calculate_font_size($font, $this->text, $width);
            
            $this->image_text($this->text, $options['text_color'], $font, $font_size);
        }

        // E. Save image
        // If $img_name is provided, use that instead of creating name from title
        $image_name = isset($options['file_name']) && $options['file_name'] ? $options['file_name'] : $image_name;
        $dst_folder = $options['dst_folder'] ?? 'images';

        $image_type = $options['image_type'] ?? 'jpg';

        $dst = JPATH_ROOT . '/' . $dst_folder . '/' . $image_name . '.' . $image_type;

        $this->save_image($this->image, $dst);
        
        imagedestroy($this->image);

        return $image_name;
    }
    
    // 05. Filter image
    public function filter_image($path, $filter = '')
    {
        if (empty($filter))
        {
            return;
        }
        
        $filter = strtoupper($filter);
        
        $image = $this->load_image($path);
        
        $result = imagefilter($image, $this->image_filters[$filter]);
        
        $this->save_image($image, $path);
        
        imagedestroy($image);
        
        return $result;
    }
    
    // 06.
    public function convert_image_to_webp($image_url)
    {
        $path = pathinfo($image_url);

        // New image URL with webp
        $new_image_url = $path['dirname'] . '/' . $path['filename'] . '.webp';
        
        $dest = JPATH_ROOT . '/' . $new_image_url;
        
        $image = $this->load_image(JPATH_ROOT . '/' . $image_url);
		
        // Create new webp image
        imagewebp($image, $dest, 80);

        imagedestroy($image);
        
        return $new_image_url;
    }
    
    // Create blank image canvas
    public function create_blank_image($width, $height)
    {
        $this->image = imagecreatetruecolor($width, $height);
        
        if ($this->image == false)
        {
            $this->set_message('Error in creating blank image');
        }
    }
    
    // Fill image with color
    public function image_fill($color)
    {
        $image_color = $this->get_image_color($color);
        
        imagefill($this->image, 0, 0, $image_color);
    }
    
    public function get_image_color($color)
    {
        list($r1, $g1, $b1) = sscanf($color, "#%02x%02x%02x");
        
        $image_color = imagecolorallocate($this->image, $r1, $g1, $b1);
        
        return $image_color;
    }
    
    // 07. 
    public function copy_image($path, $src_width, $src_height, $pct)
    {
        $src_image = $this->load_image($path);
        
        $dst_x = 0;
        $dst_y = 0;
        $src_x = 0;
        $src_y = 0;
        
        // $result = imagecopy($this->image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $src_width, $src_height);
        $result = imagecopymerge($this->image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $src_width, $src_height, $pct);
        
        imagedestroy($src_image);
        
        if ($result == false)
        {
            $this->set_message('Error in copying image');
        }
    }
    
    // Add text to image
    public function image_text($text, $text_color, $font, $font_size)
    {
        if (empty($text))
        {
            return;
        }
        
        $tb = $this->text_box($text, $font, $font_size);
        
        // Center align text
        $width = imagesx($this->image);
        $height = imagesy($this->image);
        
        $x = ($width - $tb['width'])/2;
        $y = ($height - $tb['height'])/2;
        
        $image_color = $this->get_image_color($text_color);
        
        imagettftext($this->image, $font_size, 0, $x, $y, $image_color, $font, $text);
    }
    
    // Get text box width and height
    public function text_box($text, $font, $font_size)
    {
        $box = imagettfbbox($font_size, 0, $font, $text);
        
        $tb['width'] = abs($box[4] - $box[0]);
        
        $tb['height'] = abs($box[5] - $box[1]);
        
        return $tb;
    }
    
    public function delete_image($image_url)
    {
        File::delete(JPATH_ROOT . '/' . $image_url);
    }
    
    // Load image based on its extension
    public function load_image($path)
    {
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        
        switch ($ext)
        {
            case 'jpeg' :
                $image = imagecreatefromjpeg($path);
                break;
            
            case 'jpg' :
                $image = imagecreatefromjpeg($path);
                break;
            
            case 'png' :
                $image = imagecreatefrompng($path);
                imagepalettetotruecolor($image);
                imagealphablending($image, true);
                imagesavealpha($image, true);
                break;
            
            case 'webp' :
                $image = imagecreatefromwebp($path);
                break;
            
            case 'gif' :
                $image = imagecreatefromgif($path);
        }
        
        if ($image == false)
        {
            $this->set_message('Unable to load image: ' . $path);
        }
	    
	    return $image;
    }
    
    // Save image based on its extension
    public function save_image($image, $destination)
    {
        $ext = pathinfo($destination, PATHINFO_EXTENSION);
	    
	    switch ($ext)
        {
            case 'jpeg' :
                $result = imagejpeg($image, $destination);
                break;
            
            case 'jpg' :
                $result = imagejpeg($image, $destination);
                break;
            
            case 'png' :
                $result = imagepng($image, $destination);
                break;
            
            case 'webp' :
                $result = imagewebp($image, $destination);
                break;
            
            case 'gif' :
                $result = imagegif($image, $destination);
        }
        
        if ($result == false)
        {
            $this->set_message('Error in saving image.');
        }
    }
  
  	public function calculate_font_size($font, $text, $total_width)
    {
    	$available_width = $total_width - 50;
      
      	$fs = 120;
      	while ($fs > 35)
        {          
          	$box = imagettfbbox($fs, 0, $font, $text);
        	$tb['width'] = abs($box[4] - $box[0]);
        	$tb['height'] = abs($box[5] - $box[1]);
          
          	if ($tb['width'] > $available_width)
        	{
        		$fs = $fs - 5;
        	}
      		else
      		{
        		return $fs;
      		}
        }
      
      	if ($tb['width'] > $available_width)
        {
      		$lines = ceil($tb['width']/$available_width);
          	$break_point = floor(strlen($this->text)/$lines);
          
          	$this->text = wordwrap($this->text, $break_point);
        }
      
		return $fs;
    }
    
    // Returns array of image filenames in a folder
    public function get_images($folder)
    {
        $dir = JPATH_ROOT . '/' . $folder;
        
        if (is_dir($dir))
        {
            if ($handle = opendir($dir))
			{
				while (false !== ($file = readdir($handle)))
				{
					if ($file !== '.' && $file !== '..' && $file !== 'index.html')
					{
						$files[] = $file;
					}
				}
			}
			
			closedir($handle);
			
			$i = 0;
			foreach ($files as $img)
			{
				if (!is_dir($dir . '/' . $img))
				{
					$images[$i] = $img;
					$i++;
				}
			}
        }
        
        return $images ?? '';
    }
    
    public function create_folder($path)
    {
        // $path is: JPATH_SITE . '/images/folder_name';
        
        $result = Folder::create($path);
        
        return $result;
    }
    
    // Get image properties
    public function get_image_properties($path)
    {
        $data = Image::getImageFileProperties($path);
        
        return $data;
    }
    
    public function set_message($message)
    {
        Factory::getApplication()->enqueueMessage($message);
    }

    public function create_thumbs($path, $sizes = '400x225')
    {
        if (!file_exists($path))
        {
            return;
        }
        
        $image = new Image($path);
        
        $new_images = array();

        // Array of Image Objects
        $images = $image->createThumbnails($sizes, Image::SCALE_INSIDE, null, true);

        foreach ($images as $image)
        {
            $path = $image->getPath();
            
            $directory = dirname($path);
            $pathinfo = pathinfo($path);
            $filename = $pathinfo['filename'];
            $extension = $pathinfo['extension'] ?? '';
            $dirname = $pathinfo['dirname'];
            $basename = $pathinfo['basename'];

            $properties = Image::getImageFileProperties($path);

            $new_images[] = array(
                'path' => $path,
                'filename' => $filename,
                'extension' => $extension,
                'width' => $properties->width,
                'height' => $properties->height,
                'mime' => $properties->mime,
                'filesize' => $properties->filesize,
                'orientation' => $properties->orientation,
                'dirname' => $dirname,
                'basename' => $basename,
            );
        }

        return $new_images;
    }

    // Check if thumbnail image exists, create new
    public function get_thumbnail($image)
    {
        // $image = images/folder/subfolder/myimage.jpg

        $img = HTMLHelper::cleanImageURL($image);
        $original_size = getimagesize(JPATH_SITE . '/' . $img->url);

        $pathinfo = pathinfo($img->url);
        $thumb_image = $pathinfo['dirname'] . '/thumbs/' . $pathinfo['basename'];
        $srcset = '';

        if (\file_exists(JPATH_SITE . '/' . $thumb_image))
        {
            $thumb_size = getimagesize(JPATH_SITE . '/' . $thumb_image);
            $thumb_width = $thumb_size[0];
            $thumb_height = $thumb_size[1];
        }
        else
        {
            $thumbs = $this->create_thumbs(JPATH_SITE . '/' . $img->url);
            $thumb_width = $thumbs[0]['width'];
            $thumb_height = $thumbs[0]['height'];
        }

        $srcset .= $thumb_image . ' ' . $thumb_width . 'w, ' . $img->url . ' ' . $img->attributes['width'] . 'w';
        $sizes = '(max-width: 440px) 400px, ' . $img->attributes['width'] . 'px';

        $return = array(
            'original' => array('url' => $img->url, 'width' => $original_size[0], 'height' => $original_size[1]),
            'thumb' => array('url' => $thumb_image, 'width' => $thumb_width, 'height' => $thumb_height),
            'srcset' => $srcset,
            'sizes' => $sizes,
        );

        return $return;
    }
}