Класс для обработки изображений by Koenig

3.03K
.
Koenig (25.07.2013 / 00:18)
files/users/photo/1 так
или
./files/users/photo/1
спасибо получилось
.
вот только жаль в jpg не конвертирует. а то в джоне в анкете стоит проверка на существование фото в формате jpg. придется переписать))
.
(\/)____o_O____(\/)
Vynderkind, всмысле? глянь что в папку положило, как вариант png
.
(\/)____o_O____(\/)
доделать надо будет
.
I'm the Cult of Personality...
Koenig, не сохраняет png

Warning: imagepng(): gd-png error: compression level must be 0 through 9 in /usr/home/x-rey/m/inc/class/img.php on line 142
.
I'm the Cult of Personality...
Понял в чем проблема. Роботает супер, не то что мой мосГг
.
(\/)____o_O____(\/)
BoGdAn, вроде в коментариях написано про это, у пнг качество уровнями идет, у жпег процентами
.
(\/)____o_O____(\/)
обнова
/**
* Koeimg
* 
* Обработка изображения, возможность изменения размеров пропорционально, задав ширину или длину, не пропорциональное изменение размера указать ширину и длину,
* изменение размера пропорционально в процентном соотношении, зеркальное отражение исходного изображения, получить размеры ширины или высоты изображенияб
* поворот изображение на определенный угол, сделать чб, наложение копирайта на левый верхний или левый нижний углы
* 
* @author Koenig <http://johncms.com/users/profile.php?user=6565>
* @version 1.7
*/

class Koeimg
{      
   /**
   * ширина изображения
   * 
   * @var integer 
   */
    private $width;
    /**
   * высота изображения
   * 
   * @var integer 
   */
    private $height;
    /**
   * тип изображения
   * 
   * @var string 
   */
    private $type;
    /**
   * ресурс изображения
   * 
   * @var resource 
   */
    private $img;
    /**
   * массив типов
   * 
   * @var array 
   */
    private $types = array(
        'jpg',
        'jpeg',
        'gif',
        'png'
    );
   /**
   * конструктор
   * 
   * @param string ссылка на файл изображения
   * @return resource
   */
    public function __construct($file)
    {
        if (!file_exists($file)) {
            throw new Exception('file not exists');
        }
      
        $ext = explode('.', $file);
        $ext = end($ext);
        if (!in_array($ext, $this->types)) {
            throw new Exception('unsupported image type');
        }
        $info = getimagesize($file);
        $this->width = $info[0];
        $this->height = $info[1];
        $this->type = strtolower(substr($info['mime'], strpos($info['mime'], '/') + 1));
        $func = 'imagecreatefrom' . $this->type;
        if (!function_exists($func)) {
            throw new Exception('unsupported function ' . $func);
        }
        $this->img = $func($file);
        $newimg = imagecreatetruecolor($this->width, $this->height);
        if ($this->type == 'gif') {
            $newimg = imagecreate($this->width, $this->height);
            imagecolortransparent($newimg, imagecolorallocate($newimg, 255, 255, 255));
        }
        if ($this->type == 'png') {
            imagefill($newimg, 0, 0, imagecolorallocate($newimg, 255, 255, 255));
        }
        imagecopyresampled($newimg, $this->img, 0, 0, 0, 0, $this->width, $this->height, $this->width, $this->height);
        $this->img = $newimg;
    }
   /**
   * вывод
   * 
   * @param array массив с параметрами
   * @return вывод изображение на страницу через заголовок или сохранить локально
   */
   
   
    public function out($type = 'png', $newfile = null, $quality = 9)
    {
        $quality = abs(intval($quality));
        $type = ($type == 'jpg') ? 'jpeg' : $type;
        
        $func = 'image' . $type;
        
        if (!function_exists($func)) {
            throw new Exception('unsupported function ' . $func);
        }
        if ($newfile == null) {
            header('Content-Type: image/' . $type);
        }
        else {
            $newfile = $newfile . '.' . (($type == 'jpeg') ? 'jpg' : $type);
        }
        switch ($type) {
        case 'gif':
            $func($this->img, $newfile);
            break;

        case 'jpeg':
            $quality = $quality == 9 ? 100 : $quality;
            $func($this->img, $newfile, $quality);
            break;
        case 'png':
            $quality = $quality > 9 ? 9 : $quality;
            $func($this->img, $newfile, $quality, PNG_ALL_FILTERS);
        break;    
        }
    }
    
   /**
   * наложение копирайта
   * 
   * @param string текст копирайта
   * @param interer угол 
   * 1 - левый нижний
   * 2 - левый верхний
   * @return resource 
   */
    public function copyright($text, $angle = 1)
    {
        $newimg = imagecreatetruecolor($this->width, 17);
        $white = imagecolorallocate($newimg, 0, 0, 0);
        $grey = imagecolorallocate($newimg, 128, 128, 128);
        $blue = imagecolorallocate($newimg, 0, 128, 128);
        $red = imagecolorallocate($newimg, 255, 0, 0);
        $black = imagecolorallocate($newimg, 255, 255, 255);
        imagecolortransparent($newimg, $white);
        imagefilledrectangle($newimg, 0, 0, 69, 14, $white);
        $font = 'arial.ttf';
        imagettftext($newimg, 12, 0, 5, 14, $red, $font, $text);
        imagettftext($newimg, 12, 0, 4, 13, $blue, $font, $text);
        imagettftext($newimg, 12, 0, 3, 12, $black, $font, $text);
        imagecopymerge($this->img, $newimg, 0, ($angle == 1 ? $this->height - 17 : 0) , 0, 0, $this->width, $this->height, 100);
        $this->set_sizes();
        return $this;
    }
   /**
   * отображение в зеркале
   * @return resource 
   */    
    public function mirroring()
    {
        $newimg = imagecreatetruecolor($this->width, $this->height);
        foreach(range($this->width, 0) as $range) {
            imagecopy($newimg, $this->img, $this->width - $range - 1, 0, $range, 0, 1, $this->height);
        }
        $this->img = $newimg;
        return $this;
    }
   /**
   * поворот изображения
   * @param integer угл наклона 0 - 359
   * default 90
   * @return resource 
   */    
    public function rotate($angle = 90)
    {
        $white = imagecolorallocate($this->img, 255, 255, 255);
        imagecolortransparent($this->img, $white);
        $this->img = imagerotate($this->img, $angle, $white);
        $this->set_sizes();
        return $this;
    }
   /**
   * создание чернобелого изображения
   * @return resource 
   */    
    public function grayscale()
    {
        imagefilter($this->img, IMG_FILTER_GRAYSCALE);
        return $this;
    }
   /**
   * пропорциональное изменение по высоте
   * @param integer новая длина
   * @return resource 
   */     
    public function reheight($height)
    {
        $width = $this->get_widht() * ($height / $this->get_height());
        $this->resize($width, $height);
        return $this;
    }
   /**
   * пропорциональное изменение по ширине
   * @param integer новая ширина
   * @return resource 
   */     
    public function rewidth($width)
    {
        $height = $this->get_height() * ($width / $this->get_widht());
        $this->resize($width, $height);
        return $this;
    }
   /**
   * пропорциональное изменение по ширине и высоте в процентах
   * @param integer процент
   * @return resource 
   */    
    public function scale($scale)
    {
        $width = $this->get_widht() * ($scale / 100);
        $height = $this->get_height() * ($scale / 100);
        $this->resize($width, $height);
        return $this;
    }
   /**
   * изменение по ширине и высоте
   * @param integer новая ширина
   * @param integer новая высота
   * @param integer новая высота 
   * @return resource 
   */     
    public function resize($width, $height, $x = 0, $y = 0)
    {
        $width = $x > 0 ? $width - $x : $width; 
        $height = $y > 0 ? $height - $y : $height;
        $newimg = imagecreatetruecolor($width, $height);
        imagecopyresampled($newimg, $this->img, 0, 0, $x, $y, $width, $height, $x > 0 ? $width : $this->get_widht() , $y > 0 ? $height : $this->get_height());
        $this->img = $newimg;
        $this->set_sizes();
        return $this;
    }
   /**
   * получение ширины изображения
   * @return integer
   */     
    public function set_x()
    {
        $this->width = imagesx($this->img);
        return $this;
    }
   /**
   * получение высоты изображения
   * @return integer 
   */     
    public function set_y()
    {
        $this->height = imagesy($this->img);
        return $this;
    }
    /**
    * получение заначения свойства
    * @return integer    
    */
    public function get_widht() 
    {
        return $this->width;
    }
    /**
    * получение значения свойства
    * @return integer
    */
    public function get_height() 
    {
        return $this->height;
    }
    /**
    * установка новых значений в свойства
    * @return viod
    */
    public function set_sizes()
    {
         $this->set_x();
         $this->set_y();
         return $this;
    } 
}
Прикрепленные файлы:
.
(\/)____o_O____(\/)
$a = new Koeimg('test.jpg');
$a->reheight(800)->rewidth(1000)->resize($a->get_widht(), $a->get_height(), 50, 300)->mirroring()->grayscale()->copyright('Copyright (c)')->rotate()->out();
Прикрепленные файлы:
.
(\/)____o_O____(\/)
поправил косяки, добавил метод
/**
* Koeimg
* 
* Обработка изображения, возможность изменения размеров пропорционально, задав ширину или длину, не пропорциональное изменение размера указать ширину и длину,
* изменение размера пропорционально в процентном соотношении, зеркальное отражение исходного изображения, получить размеры ширины или высоты изображенияб
* поворот изображение на определенный угол, сделать чб, наложение копирайта на левый верхний или левый нижний углы
* 
* @author Koenig <http://johncms.com/users/profile.php?user=6565>
* @version 1.8
*/

class Koeimg
{      
   /**
   * ширина изображения
   * 
   * @var integer 
   */
    private $width;
    /**
   * высота изображения
   * 
   * @var integer 
   */
    private $height;
    /**
   * тип изображения
   * 
   * @var string 
   */
    private $type;
    /**
   * ресурс изображения
   * 
   * @var resource 
   */
    private $img;
    /**
   * массив типов
   * 
   * @var array 
   */
    private $types = array(
        'jpg',
        'jpeg',
        'gif',
        'png'
    );
   /**
   * конструктор
   * 
   * @param string ссылка на файл изображения
   * @return resource
   */
    public function __construct($file)
    {
        if (!file_exists($file)) {
            throw new Exception('file not exists');
        }
      
        $ext = explode('.', $file);
        $ext = end($ext);
        if (!in_array($ext, $this->types)) {
            throw new Exception('unsupported image type');
        }
        $info = getimagesize($file);
        $this->width = $info[0];
        $this->height = $info[1];
        $this->type = strtolower(substr($info['mime'], strpos($info['mime'], '/') + 1));
        $func = 'imagecreatefrom' . $this->type;
        if (!function_exists($func)) {
            throw new Exception('unsupported function ' . $func);
        }
        $this->img = $func($file);
        $newimg = imagecreatetruecolor($this->width, $this->height);
        if ($this->type == 'gif') {
            $newimg = imagecreate($this->width, $this->height);
            imagecolortransparent($newimg, imagecolorallocate($newimg, 255, 255, 255));
        }
        if ($this->type == 'png') {
            imagefill($newimg, 0, 0, imagecolorallocate($newimg, 255, 255, 255));
        }
        imagecopyresampled($newimg, $this->img, 0, 0, 0, 0, $this->width, $this->height, $this->width, $this->height);
        $this->img = $newimg;
    }
   /**
   * вывод
   * 
   * @param array массив с параметрами
   * @return вывод изображение на страницу через заголовок или сохранить локально
   */
   
   
    public function out($type = 'png', $newfile = null, $quality = 9)
    {
        $quality = abs(intval($quality));
        $type = ($type == 'jpg') ? 'jpeg' : $type;
        
        $func = 'image' . $type;
        
        if (!function_exists($func)) {
            throw new Exception('unsupported function ' . $func);
        }
        if ($newfile == null) {
            header('Content-Type: image/' . $type);
        }
        else {
            $newfile = $newfile . '.' . (($type == 'jpeg') ? 'jpg' : $type);
        }
        switch ($type) {
        case 'gif':
            $func($this->img, $newfile);
            break;

        case 'jpeg':
            $quality = $quality == 9 ? 100 : $quality;
            $func($this->img, $newfile, $quality);
            break;
        case 'png':
            $quality = $quality > 9 ? 9 : $quality;
            $func($this->img, $newfile, $quality, PNG_ALL_FILTERS);
        break;    
        }
    }
    
   /**
   * наложение копирайта
   * 
   * @param string текст копирайта
   * @param interer угол 
   * 1 - левый нижний
   * 2 - левый верхний
   * @return resource 
   */
    public function copyright($text, $angle = 1)
    {
        $newimg = imagecreatetruecolor($this->width, 17);
        $white = imagecolorallocate($newimg, 0, 0, 0);
        $grey = imagecolorallocate($newimg, 128, 128, 128);
        $blue = imagecolorallocate($newimg, 0, 128, 128);
        $red = imagecolorallocate($newimg, 255, 0, 0);
        $black = imagecolorallocate($newimg, 255, 255, 255);
        imagecolortransparent($newimg, $white);
        imagefilledrectangle($newimg, 0, 0, 69, 14, $white);
        $font = 'arial.ttf';
        imagettftext($newimg, 12, 0, 5, 14, $red, $font, $text);
        imagettftext($newimg, 12, 0, 4, 13, $blue, $font, $text);
        imagettftext($newimg, 12, 0, 3, 12, $black, $font, $text);
        imagecopymerge($this->img, $newimg, 0, ($angle == 1 ? $this->height - 17 : 0) , 0, 0, $this->width, $this->height, 100);
        $this->set_sizes();
        return $this;
    }
   /**
   * отображение в зеркале
   * @return resource 
   */    
    public function mirroring()
    {
        $newimg = imagecreatetruecolor($this->width, $this->height);
        foreach(range($this->width, 0) as $range) {
            imagecopy($newimg, $this->img, $this->width - $range - 1, 0, $range, 0, 1, $this->height);
        }
        $this->img = $newimg;
        return $this;
    }
   /**
   * поворот изображения
   * @param integer угл наклона 0 - 359
   * default 90
   * @return resource 
   */    
    public function rotate($angle = 90)
    {
        $white = imagecolorallocate($this->img, 255, 255, 255);
        imagecolortransparent($this->img, $white);
        $this->img = imagerotate($this->img, $angle, $white);
        $this->set_sizes();
        return $this;
    }
   /**
   * создание чернобелого изображения
   * @return resource 
   */    
    public function grayscale()
    {
        imagefilter($this->img, IMG_FILTER_GRAYSCALE);
        return $this;
    }
   /**
   * пропорциональное изменение по высоте
   * @param integer новая длина
   * @return resource 
   */     
    public function reheight($height)
    {
        $width = $this->get_widht() * ($height / $this->get_height());
        $this->resize($width, $height);
        return $this;
    }
   /**
   * пропорциональное изменение по ширине
   * @param integer новая ширина
   * @return resource 
   */     
    public function rewidth($width)
    {
        $height = $this->get_height() * ($width / $this->get_widht());
        $this->resize($width, $height);
        return $this;
    }
   /**
   * пропорциональное изменение по ширине и высоте в процентах
   * @param integer процент
   * @return resource 
   */    
    public function scale($scale)
    {
        $width = $this->get_widht() * ($scale / 100);
        $height = $this->get_height() * ($scale / 100);
        $this->resize($width, $height);
        return $this;
    }
   /**
   * изменение по ширине и высоте
   * @param integer новая ширина
   * @param integer новая высота
   * @param integer новая высота 
   * @return resource 
   */     
    public function resize($width, $height, $x = 0, $y = 0)
    {
        $width = $x > 0 ? $width - $x : $width; 
        $height = $y > 0 ? $height - $y : $height;
        $newimg = imagecreatetruecolor($width, $height);
        imagecopyresampled($newimg, $this->img, 0, 0, $x, $y, $x > 0 ? $width : $this->get_widht() , $y > 0 ? $height : $this->get_height(), $x > 0 ? $width : $this->get_widht() , $y > 0 ? $height : $this->get_height());
        $this->img = $newimg;
        $this->set_sizes();
        return $this;
    }
    public function base64() 
    {
        ob_start();
        imagepng($this->img, null, 9, PNG_ALL_FILTERS);
        $temp = chunk_split(base64_encode(ob_get_contents()));
        ob_clean();
        return $temp;
    }
    
   /**
   * получение ширины изображения
   * @return integer
   */     
    public function set_x()
    {
        $this->width = imagesx($this->img);
        return $this;
    }
   /**
   * получение высоты изображения
   * @return integer 
   */     
    public function set_y()
    {
        $this->height = imagesy($this->img);
        return $this;
    }
    /**
    * получение заначения свойства
    * @return integer    
    */
    public function get_widht() 
    {
        return $this->width;
    }
    /**
    * получение значения свойства
    * @return integer
    */
    public function get_height() 
    {
        return $this->height;
    }
    public function get_type() 
    {
        return $this->type;
    }
    /**
    * установка новых значений в свойства
    * @return viod
    */
    public function set_sizes()
    {
         $this->set_x();
         $this->set_y();
         return $this;
    } 
}
Прикрепленные файлы:
Всего: 107