Настройка встроенного Watermark (Водяной знак) 2.1.0.1

Тема в разделе "Общие вопросы", создана пользователем gekin080, 11 дек 2015.

  1. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    Всем доброго времени суток! Постарался настроить watermark на opencart 2.1.0.1 Ошибки валятся везде где можно!
    добавил в catalog/model/tool/image.php после строки
    и положил файл watermark.png в папку image/
    Код:
    «$image = new Image(DIR_IMAGE . $old_image);» код:
    if ($width > 120 || $height > 120) {
    $image->watermark(new Image(DIR_IMAGE . 'watermark.png'), 'bottomright');
    }
    после чего по началу все работало, но ругалось на $watermark_position_x

    Но после совсем
    Код:
    Notice: Undefined property: Image::$info in S:\home\oc-2-0-1-1.ru\www\system\storage\modification\system\library\image.php on line 141Notice: Undefined variable: watermark_width in S:\home\oc-2-0-1-1.ru\www\system\storage\modification\system\library\image.php on line 141Notice: Undefined property: Image::$info in S:\home\oc-2-0-1-1.ru\www\system\storage\modification\system\library\image.php on line 142Notice: Undefined variable: watermark_height in S:\home\oc-2-0-1-1.ru\www\system\storage\modification\system\library\image.php on line 142
    Fatal error: Call to a member function getImage() on a non-object in S:\home\oc-2-0-1-1.ru\www\system\storage\modification\system\library\image.php on line 151

    Голову сломал, что и как делать уже не знаю! А заказчик ждет! Помогите пожалуйста!

    Код:
    <?php
    class Image {
        private $file;
        private $image;
        private $width;
        private $height;
        private $bits;
        private $mime;
    
        public function __construct($file) {
            if (file_exists($file)) {
                $this->file = $file;
    
                $info = getimagesize($file);
    
                $this->width  = $info[0];
                $this->height = $info[1];
                $this->bits = isset($info['bits']) ? $info['bits'] : '';
                $this->mime = isset($info['mime']) ? $info['mime'] : '';
    
                if ($this->mime == 'image/gif') {
                    $this->image = imagecreatefromgif($file);
                } elseif ($this->mime == 'image/png') {
                    $this->image = imagecreatefrompng($file);
                } elseif ($this->mime == 'image/jpeg') {
                    $this->image = imagecreatefromjpeg($file);
                }
            } else {
                exit('Error: Could not load image ' . $file . '!');
            }
        }
    
        public function getFile() {
            return $this->file;
        }
    
        public function getImage() {
            return $this->image;
        }
    
        public function getWidth() {
            return $this->width;
        }
    
        public function getHeight() {
            return $this->height;
        }
    
        public function getBits() {
            return $this->bits;
        }
    
        public function getMime() {
            return $this->mime;
        }
    
        public function save($file, $quality = 90) {
            $info = pathinfo($file);
    
            $extension = strtolower($info['extension']);
    
            if (is_resource($this->image)) {
                if ($extension == 'jpeg' || $extension == 'jpg') {
                    imagejpeg($this->image, $file, $quality);
                } elseif ($extension == 'png') {
                    imagepng($this->image, $file);
                } elseif ($extension == 'gif') {
                    imagegif($this->image, $file);
                }
    
                imagedestroy($this->image);
            }
        }
    
        public function resize($width = 0, $height = 0, $default = '') {
            if (!$this->width || !$this->height) {
                return;
            }
    
            $xpos = 0;
            $ypos = 0;
            $scale = 1;
    
            $scale_w = $width / $this->width;
            $scale_h = $height / $this->height;
    
            if ($default == 'w') {
                $scale = $scale_w;
            } elseif ($default == 'h') {
                $scale = $scale_h;
            } else {
                $scale = min($scale_w, $scale_h);
            }
    
            if ($scale == 1 && $scale_h == $scale_w && $this->mime != 'image/png') {
                return;
            }
    
            $new_width = (int)($this->width * $scale);
            $new_height = (int)($this->height * $scale);
            $xpos = (int)(($width - $new_width) / 2);
            $ypos = (int)(($height - $new_height) / 2);
    
            $image_old = $this->image;
            $this->image = imagecreatetruecolor($width, $height);
    
            if ($this->mime == 'image/png') {
                imagealphablending($this->image, false);
                imagesavealpha($this->image, true);
                $background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
                imagecolortransparent($this->image, $background);
            } else {
                $background = imagecolorallocate($this->image, 255, 255, 255);
            }
    
            imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
    
            imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->width, $this->height);
            imagedestroy($image_old);
    
            $this->width = $width;
            $this->height = $height;
        }
    
        public function watermark($watermark, $position = 'bottomright') {
            switch($position) {
                case 'topleft':
                    $watermark_pos_x = 0;
                    $watermark_pos_y = 0;
                    break;
                case 'topright':
                    $watermark_pos_x = $this->width - $watermark->getWidth();
                    $watermark_pos_y = 0;
                    break;
                case 'bottomleft':
                    $watermark_pos_x = 0;
                    $watermark_pos_y = $this->height - $watermark->getHeight();
                    break;
    
    case 'center':
                $watermark_pos_x = ($this->info['width']- $watermark_width)/2;
                $watermark_pos_y = ($this->info['height']- $watermark_height)/2;
                break;
    
                case 'bottomright':
                    $watermark_pos_x = $this->width - $watermark->getWidth();
                    $watermark_pos_y = $this->height - $watermark->getHeight();
                    break;
            }
    
            imagecopy($this->image, $watermark->getImage(), $watermark_pos_x, $watermark_pos_y, 0, 0, $watermark->getWidth(), $watermark->getHeight());
    
            imagedestroy($watermark->getImage());
        }
    
        public function crop($top_x, $top_y, $bottom_x, $bottom_y) {
            $image_old = $this->image;
            $this->image = imagecreatetruecolor($bottom_x - $top_x, $bottom_y - $top_y);
    
            imagecopy($this->image, $image_old, 0, 0, $top_x, $top_y, $this->width, $this->height);
            imagedestroy($image_old);
    
            $this->width = $bottom_x - $top_x;
            $this->height = $bottom_y - $top_y;
        }
    
        public function rotate($degree, $color = 'FFFFFF') {
            $rgb = $this->html2rgb($color);
    
            $this->image = imagerotate($this->image, $degree, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
    
            $this->width = imagesx($this->image);
            $this->height = imagesy($this->image);
        }
    
        private function filter() {
            $args = func_get_args();
    
            call_user_func_array('imagefilter', $args);
        }
    
        private function text($text, $x = 0, $y = 0, $size = 5, $color = '000000') {
            $rgb = $this->html2rgb($color);
    
            imagestring($this->image, $size, $x, $y, $text, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
        }
    
        private function merge($merge, $x = 0, $y = 0, $opacity = 100) {
            imagecopymerge($this->image, $merge->getImage(), $x, $y, 0, 0, $merge->getWidth(), $merge->getHeight(), $opacity);
        }
    
        private function html2rgb($color) {
            if ($color[0] == '#') {
                $color = substr($color, 1);
            }
    
            if (strlen($color) == 6) {
                list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
            } elseif (strlen($color) == 3) {
                list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
            } else {
                return false;
            }
    
            $r = hexdec($r);
            $g = hexdec($g);
            $b = hexdec($b);
    
            return array($r, $g, $b);
        }
    }
    
     
  2. Ален

    Ален Эксперт

    Сообщения:
    2.056
    Симпатии:
    640
    изменения нужно вносить в файл catalog\model\tool\image.php

    Об этом написано в инструкции той!
     
  3. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    Именно туда и вносил вот:
    <?php
    class ModelToolImage extends Model {
    public function resize($filename, $width, $height) {
    if (!is_file(DIR_IMAGE . $filename)) {
    return;
    }

    $extension = pathinfo($filename, PATHINFO_EXTENSION);

    $old_image = $filename;
    $new_image = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;

    if (!is_file(DIR_IMAGE . $new_image) || (filectime(DIR_IMAGE . $old_image) > filectime(DIR_IMAGE . $new_image))) {
    $path = '';

    $directories = explode('/', dirname(str_replace('../', '', $new_image)));

    foreach ($directories as $directory) {
    $path = $path . '/' . $directory;

    if (!is_dir(DIR_IMAGE . $path)) {
    @mkdir(DIR_IMAGE . $path, 0777);
    }
    }

    list($width_orig, $height_orig) = getimagesize(DIR_IMAGE . $old_image);

    if ($width_orig != $width || $height_orig != $height) {
    $image = new Image(DIR_IMAGE . $old_image);

    if ($width > 120 || $height > 120) {
    $image->watermark(new Image(DIR_IMAGE . 'watermark.png'), 'center');
    }
    $image->resize($width, $height);
    $image->save(DIR_IMAGE . $new_image);
    } else {
    copy(DIR_IMAGE . $old_image, DIR_IMAGE . $new_image);
    }
    }

    if ($this->request->server['HTTPS']) {
    return $this->config->get('config_ssl') . 'image/' . $new_image;
    } else {
    return $this->config->get('config_url') . 'image/' . $new_image;
    }
    }
    }
     
  4. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    инструкцию не подкинешь?
     
  5. Ален

    Ален Эксперт

    Сообщения:
    2.056
    Симпатии:
    640
    ваши ошибки говорят о обратном. Да еще и не понятно, вы еще и модификатор установили и изменения что ли вручную внесли??
     
  6. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    между действиями я перезаливал /system и /catalog.
     
  7. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
  8. Ален

    Ален Эксперт

    Сообщения:
    2.056
    Симпатии:
    640
    Перезаливал - это подход "школьника" (уж простите за сравнение), а не специалиста который делает для заказчика. Тоже самое что сказать , 100 раз перезагрузил комп, а он не заработал. Так что пусть ждет заказчик пока не разберетесь.

    Будьте точнее, что именно сделали, что лежит в папке system, что загружено в модификаторы, файлы которые изменили, восстановлены?

    И точно какая у вас версия ?? 2.0.1.1 (так в названии сайта написано) или все же 2.1.0.1 ???
     
  9. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    Не каких обид! Версия точно та! И вынужден признать где-то вы правы! Установил чистый openCart 2.1.0.1 - Провел действия без модификаторов и все заработало! Большое спасибо на указание ошибок! Будим учиться!

    Можно еще подзатыльника? Как же его все-таки в центр вывести?
    я так понимаю когда в catalog/model/tool/image.php впервые вносишь изменения нужно прописать ему вместо bottomright - center или???
     
  10. Ален

    Ален Эксперт

    Сообщения:
    2.056
    Симпатии:
    640
    такого нет. Только по углам Смотрите в system\library\image.php
    В принципе и по центру можно, но сейчас лень. Сами не сообразите, позже сделаю..
     
  11. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    В каком файле вносить изменения? Это очень поможет!
     
  12. Ален

    Ален Эксперт

    Сообщения:
    2.056
    Симпатии:
    640
  13. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    Вопрос с watermark решен!
    в файле system/library/image.php в switch() дописать
    PHP:
    case 'center':
                    
    $watermark_pos_x = ($this->width $watermark->getWidth())/2;
                    
    $watermark_pos_y = ($this->height $watermark->getHeight())/2;
                    break;
    После чего в файле catalog/model/tool/image.php заменить 'bottomright' на 'center'
    PHP:
                    $image->watermark(new Image(DIR_IMAGE 'watermark.png'), 'center');
    Спасибо Ален! Вдохновил!
     
    Последнее редактирование: 25 янв 2016
    Vlad нравится это.
  14. Vlad

    Vlad Эксперт

    Сообщения:
    4.129
    Симпатии:
    999
  15. gooldbee

    gooldbee Новичок

    Сообщения:
    6
    Симпатии:
    0
    сделал всё получилось! спасибо!
    только у меня получился только один знак "Simhop"
    а как сделать как на втором примере? помогите пожалуйста
    Скриншот 24-01-2016 214227.png Скриншот 24-01-2016 214105.png
     
  16. gekin080

    gekin080 Новичок

    Сообщения:
    9
    Симпатии:
    2
    Доброго времени суток! Для такого watermark-a используйте заранее подготовленный .png файл на котором отрисована надпись повторяющаяся по диогонали. Далее если у Вас фото разного размера, то создайте несколько watermark( пример watermark-320.png, watermark-240.png) и подгружайтеи watermark соответствующего размера пример:

    PHP:
    if( $this->width 320) {
    $image->watermark(new Image(DIR_IMAGE 'watermark-320.png'), 'center');
    }
    Или через switch! Если этого не зделать, то ваш watermark будет натигиваться на все размеры.
     
    Romans нравится это.
  17. gooldbee

    gooldbee Новичок

    Сообщения:
    6
    Симпатии:
    0
    спасибо попробую отпишусь , а как сделать чтобы воденой знак был только на тех картинках который открывают а не на всех что на сайте , чтобы когда товар открывают там и загружался знак ?
     
  18. Quip

    Quip Новичок

    Сообщения:
    28
    Симпатии:
    7
    Здравствуйте! Подскажите пожалуйста как реализовать watermark на русской сборке 2.3.0.2 rs3?
    Код:
    <?php
    class Image {
        private $file;
        private $image;
        private $width;
        private $height;
        private $bits;
        private $mime;
    
        public function __construct($file) {
            if (file_exists($file)) {
                $this->file = $file;
    
                $info = getimagesize($file);
    
                $this->width  = $info[0];
                $this->height = $info[1];
                $this->bits = isset($info['bits']) ? $info['bits'] : '';
                $this->mime = isset($info['mime']) ? $info['mime'] : '';
    
                if ($this->mime == 'image/gif') {
                    $this->image = imagecreatefromgif($file);
                } elseif ($this->mime == 'image/png') {
                    $this->image = imagecreatefrompng($file);
                } elseif ($this->mime == 'image/jpeg') {
                    $this->image = imagecreatefromjpeg($file);
                }
            } else {
                exit('Error: Could not load image ' . $file . '!');
            }
        }
    
        public function getFile() {
            return $this->file;
        }
    
        public function getImage() {
            return $this->image;
        }
    
        public function getWidth() {
            return $this->width;
        }
    
        public function getHeight() {
            return $this->height;
        }
    
        public function getBits() {
            return $this->bits;
        }
    
        public function getMime() {
            return $this->mime;
        }
    
        public function save($file, $quality = 90) {
            $info = pathinfo($file);
    
            $extension = strtolower($info['extension']);
    
            if (is_resource($this->image)) {
                if ($extension == 'jpeg' || $extension == 'jpg') {
                    imagejpeg($this->image, $file, $quality);
                } elseif ($extension == 'png') {
                    imagepng($this->image, $file);
                } elseif ($extension == 'gif') {
                    imagegif($this->image, $file);
                }
    
                imagedestroy($this->image);
            }
        }
    
        public function resize($width = 0, $height = 0, $default = '') {
            if (!$this->width || !$this->height) {
                return;
            }
    
            $xpos = 0;
            $ypos = 0;
            $scale = 1;
    
            $scale_w = $width / $this->width;
            $scale_h = $height / $this->height;
    
            if ($default == 'w') {
                $scale = $scale_w;
            } elseif ($default == 'h') {
                $scale = $scale_h;
            } else {
                $scale = min($scale_w, $scale_h);
            }
    
            if ($scale == 1 && $scale_h == $scale_w && $this->mime != 'image/png') {
                return;
            }
    
            $new_width = (int)($this->width * $scale);
            $new_height = (int)($this->height * $scale);
            $xpos = (int)(($width - $new_width) / 2);
            $ypos = (int)(($height - $new_height) / 2);
    
            $image_old = $this->image;
            $this->image = imagecreatetruecolor($width, $height);
    
            if ($this->mime == 'image/png') {
                imagealphablending($this->image, false);
                imagesavealpha($this->image, true);
                $background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
                imagecolortransparent($this->image, $background);
            } else {
                $background = imagecolorallocate($this->image, 255, 255, 255);
            }
    
            imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
    
            imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->width, $this->height);
            imagedestroy($image_old);
    
            $this->width = $width;
            $this->height = $height;
        }
    
        public function watermark($watermark, $position = 'bottomright') {
            switch($position) {
                case 'topleft':
                    $watermark_pos_x = 0;
                    $watermark_pos_y = 0;
                    break;
                case 'topcenter':
                    $watermark_pos_x = intval(($this->width - $watermark->getWidth()) / 2);
                    $watermark_pos_y = 0;
                    break;
                case 'topright':
                    $watermark_pos_x = $this->width - $watermark->getWidth();
                    $watermark_pos_y = 0;
                    break;
                case 'middleleft':
                    $watermark_pos_x = 0;
                    $watermark_pos_y = intval(($this->height - $watermark->getHeight()) / 2);
                    break;
                case 'middlecenter':
                    $watermark_pos_x = intval(($this->width - $watermark->getWidth()) / 2);
                    $watermark_pos_y = intval(($this->height - $watermark->getHeight()) / 2);
                    break;
                case 'middleright':
                    $watermark_pos_x = $this->width - $watermark->getWidth();
                    $watermark_pos_y = intval(($this->height - $watermark->getHeight()) / 2);
                    break;
                case 'bottomleft':
                    $watermark_pos_x = 0;
                    $watermark_pos_y = $this->height - $watermark->getHeight();
                    break;
                case 'bottomcenter':
                    $watermark_pos_x = intval(($this->width - $watermark->getWidth()) / 2);
                    $watermark_pos_y = $this->height - $watermark->getHeight();
                    break;
                case 'bottomright':
                    $watermark_pos_x = $this->width - $watermark->getWidth();
                    $watermark_pos_y = $this->height - $watermark->getHeight();
                    break;
            }
     
            imagealphablending( $this->image, true );
            imagesavealpha( $this->image, true );
            imagecopy($this->image, $watermark->getImage(), $watermark_pos_x, $watermark_pos_y, 0, 0, $watermark->getWidth(), $watermark->getHeight());
    
            imagedestroy($watermark->getImage());
        }
    
        public function crop($top_x, $top_y, $bottom_x, $bottom_y) {
            $image_old = $this->image;
            $this->image = imagecreatetruecolor($bottom_x - $top_x, $bottom_y - $top_y);
    
            imagecopy($this->image, $image_old, 0, 0, $top_x, $top_y, $this->width, $this->height);
            imagedestroy($image_old);
    
            $this->width = $bottom_x - $top_x;
            $this->height = $bottom_y - $top_y;
        }
    
        public function rotate($degree, $color = 'FFFFFF') {
            $rgb = $this->html2rgb($color);
    
            $this->image = imagerotate($this->image, $degree, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
    
            $this->width = imagesx($this->image);
            $this->height = imagesy($this->image);
        }
    
        private function filter() {
            $args = func_get_args();
    
            call_user_func_array('imagefilter', $args);
        }
    
        private function text($text, $x = 0, $y = 0, $size = 5, $color = '000000') {
            $rgb = $this->html2rgb($color);
    
            imagestring($this->image, $size, $x, $y, $text, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
        }
    
        private function merge($merge, $x = 0, $y = 0, $opacity = 100) {
            imagecopymerge($this->image, $merge->getImage(), $x, $y, 0, 0, $merge->getWidth(), $merge->getHeight(), $opacity);
        }
    
        private function html2rgb($color) {
            if ($color[0] == '#') {
                $color = substr($color, 1);
            }
    
            if (strlen($color) == 6) {
                list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
            } elseif (strlen($color) == 3) {
                list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
            } else {
                return false;
            }
    
            $r = hexdec($r);
            $g = hexdec($g);
            $b = hexdec($b);
    
            return array($r, $g, $b);
        }
    }
    
    Код:
    <?php
    class ModelToolImage extends Model {
        public function resize($filename, $width, $height) {
            if (!is_file(DIR_IMAGE . $filename) || substr(str_replace('\\', '/', realpath(DIR_IMAGE . $filename)), 0, strlen(DIR_IMAGE)) != DIR_IMAGE) {
                return;
            }
    
            $extension = pathinfo($filename, PATHINFO_EXTENSION);
    
            $image_old = $filename;
            $image_new = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . (int)$width . 'x' . (int)$height . '.' . $extension;
    
            if (!is_file(DIR_IMAGE . $image_new) || (filectime(DIR_IMAGE . $image_old) > filectime(DIR_IMAGE . $image_new))) {
                list($width_orig, $height_orig, $image_type) = getimagesize(DIR_IMAGE . $image_old);
             
                if (!in_array($image_type, array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) {
                    return DIR_IMAGE . $image_old;
                }
                     
                $path = '';
    
                $directories = explode('/', dirname($image_new));
    
                foreach ($directories as $directory) {
                    $path = $path . '/' . $directory;
    
                    if (!is_dir(DIR_IMAGE . $path)) {
                        @mkdir(DIR_IMAGE . $path, 0777);
                    }
                }
    
                if ($width_orig != $width || $height_orig != $height) {
                    $image = new Image(DIR_IMAGE . $image_old);
                    $image->resize($width, $height);
                    $image->save(DIR_IMAGE . $image_new);
                } else {
                    copy(DIR_IMAGE . $image_old, DIR_IMAGE . $image_new);
                }
            }
     
            $image_new = str_replace(' ', '%20', $image_new);  // fix bug when attach image on email (gmail.com). it is automatic changing space " " to +
     
            if ($this->request->server['HTTPS']) {
                return $this->config->get('config_ssl') . 'image/' . $image_new;
            } else {
                return $this->config->get('config_url') . 'image/' . $image_new;
            }
        }
    }
    
    От темы зависит работоспособность? Тема Journal 2.7.6. На стандартной тоже ничего не отобразилось.
     
    Последнее редактирование: 26 сен 2016
  19. Quip

    Quip Новичок

    Сообщения:
    28
    Симпатии:
    7
    После внесенных изменений с изображениями необходимо что-то делать? Удалять с сервера, загружать? Или watermark должен появиться поверх созданных изображений? Можно ли удалить всё из папки /image/cache/ ? Система их пересоздаст?
     
  20. Vlad

    Vlad Эксперт

    Сообщения:
    4.129
    Симпатии:
    999
    да. Все решения только для стандартной поставки.

    да. Обновить модификаторы. Очистить кеш изображений, очистить кеш браузера.
     
    Quip нравится это.