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

2.96K
.
(\/)____o_O____(\/)
Натолкнула на мысль тема Класс для работы с изображением
Документатор из меня плохой, точнее ни какой, но думаю не сложно разобраться будет
class Koeimg
{
    private $width;
    private $height;
    private $type;
    private $img;
    private $imgtypes = array(
        'jpg',
        'jpeg',
        'gif',
        'png'
    );
    public function __construct($imgfile)
    {
        if (!file_exists($imgfile)) {
            throw new Exception('file not exists');
        }
        $imgtypes = array(
            'jpg',
            'jpeg',
            'gif',
            'png'
        );
        $ext = explode('.', $imgfile);
        $ext = end($ext);
        if (!in_array($ext, $this->imgtypes)) {
            throw new Exception('unsupported image type');
        }
        $info = getimagesize($imgfile);
        $this->width = $info[0];
        $this->height = $info[1];
        $this->type = $info['mime'];
        $this->type = strtolower(substr($this->type, strpos($this->type, '/') + 1));
        $imgfunc = 'imagecreatefrom' . $this->type;
        if (!function_exists($imgfunc)) {
            throw new Exception('unsupported function ' . $imgfunc);
        }
        $this->img = $imgfunc($imgfile);
        $tmp = imagecreatetruecolor($this->width, $this->height);
        if ($this->type == 'gif') {
            $tmp = imagecreate($this->width, $this->height);
            imagecolortransparent($tmp, imagecolorallocate($tmp, 255, 255, 255));
        }
        if ($this->type == 'png') {
            imagefill($tmp, 0, 0, imagecolorallocate($tmp, 255, 255, 255));
        }
        else if ($this->type == 'gif') {
            imagecolortransparent($tmp, imagecolorallocate($tmp, 255, 255, 255));
        }
        imagecopyresampled($tmp, $this->img, 0, 0, 0, 0, $this->width, $this->height, $this->width, $this->height);
        $this->img = $tmp;
    }
    public function imgout($mode = array())
    {
        $defaultmode = array(
            'type' => 'png',
            'newfile' => null,
            'quality' => 9,
            'filters' => PNG_ALL_FILTERS
        );
        foreach($defaultmode as $k => $v) {
            if (!isset($mode[$k])) {
                $mode[$k] = $v;
            }
        }
        $imgfuncout = 'image' . $mode['type'];
        if (!function_exists($imgfuncout)) {
            throw new Exception('unsupported function ' . $imgfuncout);
        }
        if ($mode['newfile'] == null) {
            header('Content-Type: image/' . $mode['type']);
        }
        else {
            $mode['newfile'] = $mode['newfile'] . '.' . $mode['type'];
        }
        switch ($mode['type']) {
        case 'gif':
            $imgfuncout($this->img, $mode['newfile']);
            break;

        case 'jpeg':
            $imgfuncout($this->img, $mode['newfile'], $mode['quality']);
            break;

        default:
            $imgfuncout($this->img, $mode['newfile'], $mode['quality'], $mode['filters']);
            break;
        }
    }
    public function copyright($text, $angle = 1)
    {
        $im = imagecreatetruecolor($this->width, 17);
        $white = imagecolorallocate($im, 0, 0, 0);
        $grey = imagecolorallocate($im, 128, 128, 128);
        $blue = imagecolorallocate($im, 0, 128, 128);
        $red = imagecolorallocate($im, 255, 0, 0);
        $black = imagecolorallocate($im, 255, 255, 255);
        imagecolortransparent($im, $white);
        imagefilledrectangle($im, 0, 0, 69, 14, $white);
        $font = 'arial.ttf';
        imagettftext($im, 12, 0, 5, 14, $red, $font, $text);
        imagettftext($im, 12, 0, 4, 13, $blue, $font, $text);
        imagettftext($im, 12, 0, 3, 12, $black, $font, $text);
        imagecopymerge($this->img, $im, 0, ($angle == 1 ? $this->height - 17 : 0) , 0, 0, $this->width, $this->height, 100);
    }
    public function mirroring()
    {
        $new_image = imagecreatetruecolor($this->width, $this->height);
        foreach(range($this->width, 0) as $range) {
            imagecopy($new_image, $this->img, $this->width - $range - 1, 0, $range, 0, 1, $this->height);
        }
        $this->img = $new_image;
    }
    public function rotate($angle = 90)
    {
        $white = imagecolorallocate($this->img, 255, 255, 255);
        imagecolortransparent($this->img, $white);
        $this->img = imagerotate($this->img, $angle, $white);
        $this->width = $this->newx();
        $this->height = $this->newy();
    }
    public function grayscale()
    {
        imagefilter($this->img, IMG_FILTER_GRAYSCALE);
    }
    public function reheight($height)
    {
        $width = $this->newx() * ($height / $this->newy());
        $this->resize($width, $height);
    }
    public function rewidth($width)
    {
        $height = $this->newy() * ($width / $this->newx());
        $this->resize($width, $height);
    }
    public function scale($scale)
    {
        $width = $this->newx() * ($scale / 100);
        $height = $this->newy() * ($scale / 100);
        $this->resize($width, $height);
    }
    public function resize($width, $height)
    {
        $newimg = imagecreatetruecolor($width, $height);
        imagecopyresampled($newimg, $this->img, 0, 0, 0, 0, $width, $height, $this->newx() , $this->newy());
        $this->img = $newimg;
        $this->width = $this->newx();
        $this->height = $this->newy();
    }
    public function newx()
    {
        return imagesx($this->img);
    }
    public function newy()
    {
        return imagesy($this->img);
    }
    public function __destruct()
    {
        imagedestroy($this->img);
        foreach($this as $key => $value) {
            unset($this->$key);
        }
    }
}
Прикрепленные файлы:
.
Koenig
(\/)____o_O____(\/)
как работает?
шрифт прикрепляю

$img = new koeimg('test3.png'); // картинка

$img->mirroring(); // зеркально перевернуть

$img->grayscale();  // чб вариант

#$img->rotate(); // крутить на 90 градусов по умолчанию
#$img->rotate(180); // 180

$img->copyright('Copyright (c) Copyright (c) Copyright (c)');  /* копирайт левый нижний угол */
#$img->copyright('Copyright (c) Copyright (c) Copyright (c)', 2); /* копирайт левый верхний угол */
$img->rewidth(1400); // пропорционально сделать картинку с шириной в 1400
$img->reheight(500); // пропорционально сделать картинку с длиной в 500 

$img->scale(200); // увеличить картинку на 200%
#$img->scale(33); // уменьшить картинку до 33%
#$img->resize(200, 300); // сделать 200х300



$args = array('type' => 'jpeg', 'newfile' => 'testimg', 'quality' => 100); // аргументы для вывода
$img->imgout($args); 
#$img->imgout(); // выдаст png на экран
Прикрепленные файлы:
.
Блиносвёрт ?
Koenig, круто молодец
.
отлично
.
(\/)____o_O____(\/)
пример
Прикрепленные файлы:
.
Tadochi
По моему лучшее определять расширение так
$ext = pathinfo($imgfile, PATHINFO_EXTENSION);
.
(\/)____o_O____(\/)
Tadochi, pathinfo не везде работает, так надежнее
.
(\/)____o_O____(\/)
потестите кому не трудно, разные варианты с исходным и выходным изображением, опереции в разном порядке, просто где то может появиться ошибка или пропасть прозрачность
.
(\/)____o_O____(\/)
давно лежал класс, для кфм писал его, потом встрою его туда
.
I'm the Cult of Personality...
Koenig, спасиб за клас.
И новость
давно лежал класс, для кфм писал его, потом встрою его туда
Всего: 107