Позиционирование watermark при наложении через PHP

artik77

Kochubey
Привет ребята. Подскажите пожалуйста решение. При загрузке изображения - watermark клеится строго по центру картинки. Как настроить чтобы оно например было в правом нижнем углу?
Вот код который преобразует:
PHP:
//Конфиг для картинок
          $config = array(
            0        => null, //Оригинальное изображение сохраняется без изменений
            'thumb'  => array(
              Image::RESIZE => array('width' => 160, 'height' => 120)
            ),
            'medium' => array(
              Image::RESIZE => array('width' => 300, 'height' => 230)
            ),
            'big'    => array(
              Image::RESIZE => array('width' => 800, 'height' => 800, 'watermark' => DOCROOT . '/inc/watermark.png')
            ),
          );
//ЗАДАЕМ КАК БУДЕТ ПЕРЕЖАТО ИЗОБРАЖЕНИЕ
                foreach ($config as $size => $arr) {
                  if (is_array($arr)) {
                    foreach ($arr as $action => $attr) {
                      if (empty ($attr['height'])) {
                        $attr['height'] = null;
                      }
                      if (empty ($attr['width'])) {
                        $attr['width'] = null;
                      }

                      $name = $new_name . (empty ($attr['one']) ? '_' . $i : '');

                      $image->clean();
                      switch ($action) {
                        case Image::CROP:
                          $image->crop($attr['width'], $attr['height']);
                          break;
                        case Image::RESIZE:
                          $image->resize($attr['width'], $attr['height'], (!empty($attr['non_prop']) ? true : false));
                          break;
                        default:
                          continue;
                      }

                      if (isset ($attr['watermark'])) {
                        $image->watermark($attr['watermark']);
                      }
                    }
                  } else {
                    $name = $new_name . (empty ($attr['one']) ? '_' . $i : '');
                  }
                //СОХРАНЯЕМ ФАЙЛ
                  $image->save($name . (is_numeric($size) ? '' : '_' . $size) . '.jpg');
                }
                //Удаляем временный файл
                unlink($tmp_filename);

                echo '1';
              } else {
                echo 'Error yeah!';
              }

              break;
          }
        }
 

AmdY

Пью пиво
Команда форума
ну, тебе нужно смотреть метод Image::watermark, остальной код не имеет отношение в задаче
 

artik77

Kochubey
Вот нашел файл где это происходит
PHP:
<?php

    class Image {

        private $source;
        private $width;
        private $height;

        private $watermark;
        private $watermark_height;
        private $watermark_width;
        private $watermark_x;
        private $watermark_y;

        private $action = array();
        private $errors = array();

        private $image = NULL;
        private $crop_height;
        private $crop_width;
        private $resize_height;
        private $resize_width;
        private $non_prop;

        const CROP = 10;
        const RESIZE = 20;

        /**
        * Конструктыр
        */
        function __construct( $source = NULL ) {
            if ( !is_null ( $source ) ) $this->load( $source );
        }

        /**
        * Ошибки, если они есть или false
        */
        public function errors() {
            if ( count ( $this->errors ) ) return $this->errors;
            else return false;
        }

        /**
        * Загрузка изображения из файла
        */
        function load ( $source ) {
            if ( !is_file($source) ) {
                $this->errors[] = 'Указанный файл не существует';
                return $this;
            }

            //Получаем информацию о файле
            if ( !$info = getimagesize( $source ) ) {
                $this->errors[] = 'Указанный файл не является изображением';
                return $this;
            }

            //В зависимости от типа изображения открываем файл
            if ( !$this->source = self::loadFromFile( $source, $info[2] ) ) {
                $this->errors[] = 'Указанный файл не является изображением допустимого формата';
                return $this;
            }

            //Размеры
            $this->width = $info[0];
            $this->height = $info[1];
            return $this;
        }

        /**
        * Указываем, что новое изображение обрезается
        */
        function crop ( $width = NULL, $height = NULL ) {
            if ( !is_null( $width ) ) $this->crop_width = $width;
            if ( !is_null( $height ) ) $this->crop_height = $height;
            $this->action[] = self::CROP;
            return $this;
        }

        /**
        * Указываем, что новое изображение ужимается
        */
        function resize ( $width = NULL, $height = NULL, $non_prop = false ) {
            if ( !is_null( $width ) ) $this->resize_width = $width;
            if ( !is_null( $height ) ) $this->resize_height = $height;
            $this->non_prop  = $non_prop;
            $this->action[] = self::RESIZE;
            return $this;
        }

        /**
        * Создание объекта IMAGE из файла
        * Если тип не указан загрузка более ресурсоемкая
        */
        private static function loadFromFile ( $source, $type = NULL ) {
            switch ( $type ) {
                case IMAGETYPE_JPEG:    return imagecreatefromjpeg( $source ); break;
                case IMAGETYPE_GIF:    return imagecreatefromgif( $source ); break;
                case IMAGETYPE_PNG:    return imagecreatefrompng( $source ); break;
                case IMAGETYPE_BMP:    return imagecreatefromwbmp( $source ); break;
                default:                return imagecreatefromstring( file_get_contents( $source ) );
            }
        }

        /**
        * Ставим на новом изображении ватермарк
        */
        function watermark ( $source, $x = NULL, $y = NULL ) {
            if ( !is_file( $source ) ) {
                $this->errors[] = 'Файл водяного знака не существует';
                return $this;
            }

            //Получаем информацию о файле
            if ( !$info = getimagesize( $source ) ) {
                $this->errors[] = 'Указанный водяной знак не является изображением';
                return $this;
            }

            //В зависимости от типа изображения открываем файл
            if ( !$this->watermark = self::loadFromFile( $source, $info[2] ) ) {
                $this->errors[] = 'Указанный водяной знак не является изображением допустимого формата';
                return $this;
            }

            //Размеры
            $this->watermark_width = $info[0];
            $this->watermark_height = $info[1];
            $this->watermark_x = $x;
            $this->watermark_y = $y;
            return $this;

        }

        /**
        * Применяем все изменения
        */
        function make () {
            if ( $this->errors() ) return X::Debug($this->errors);
            if ( is_array( $this->action ) ) foreach ( $this->action as $act ) {
                switch ($act) {
                    case self::CROP:
                        $this->image = self::makeCrop(($this->image?$this->image:$this->source), $this->crop_width, $this->crop_height );
                        break;
                    case self::RESIZE:
                        $this->image = self::makeResize(($this->image?$this->image:$this->source), $this->resize_width, $this->resize_height, $this->non_prop );
                        break;
                }
            }
            if ( $this->watermark ) {
                $this->image = self::makeWatermark(($this->image?$this->image:$this->source), $this->watermark );
            }
        }

        public static function makeWatermark ( $source, $watermark ) {
            $s_width = imagesx($source);
            $s_height = imagesy($source);
            $w_width = imagesx($watermark);
            $w_height = imagesy($watermark);
            imagecopy ( $source, $watermark, ceil(($s_width-$w_width)/2), ceil (($s_height-$w_height)/2), 0, 0, $w_width, $w_height );
            return $source;
        }

        /**
        * Непосредственно ужималка
        */
        public static function makeResize ( $source, $width = NULL, $height = NULL, $non_prop = false ) {
            $orig_width = imagesx( $source );
            $orig_height = imagesy( $source );

            $resize_height = $resize_width = 0;

//            echo 'Width: '.$width.' / Orig: '.$orig_width.'<br>'
//                .'Height: '.$height.' / Orig: '.$orig_height.'<br>';

            $new_height = $height;
            if ( $width < $orig_width ) {
                $new_height = ceil( $orig_height / ($orig_width/$width) );
                if ( $new_height > $height ) $new_height = $height;
//                echo 'Heigh cut: '.$new_height.'<br>';
            } else {
                $width = $orig_width;
//                echo 'Width equal to '.$width.'<br>';
            }

            if ( $new_height < $orig_height ) {
//                $new_height = $orig_height;
                $new_width = ceil( $orig_width * ($new_height/$orig_height) );
                if ( $new_width > $width ) {
                    $new_height = ceil( $orig_height / ($orig_width/$width) );
//                    echo 'Width still too big, cutting to '.$width.' x '.$new_height.'<br>';
                } else $width = $new_width;
//                echo 'Height < Orig => Width equal '.$width.'<br>';
            } else {
                $new_height = $height;
                $width = ceil( $orig_width / ($orig_height/$new_height) );
//                echo 'Height > Orig => Width equal '.$width.', Height stays '.$new_height.'<br>';
            }
            $height = $new_height;
//            echo 'Final: '.$width.' x '.$height.'<br>';

            $image = imagecreatetruecolor ( $width, $height );
            imagecopyresampled ( $image, $source, 0, 0, 0, 0, $width, $height, $orig_width, $orig_height );
            return $image;
        }

        public static function makeCrop ( $source, $width = NULL, $height = NULL ) {
            $orig_width = imagesx( $source );
            $orig_height = imagesy( $source );
            $image = imagecreatetruecolor ( $width, $height );
            imagecopy( $image, $source, 0, 0, 0, 0, $width, $height );
            return $image;
        }

        function show ( $return = false ) {
           
        }

        function save ( $file ) {
            $this->make();
            if ( is_null ( $this->image ) ) $this->image = $this->source;
            return imagejpeg( $this->image, $file );
        }

        function clean ( $save_source = true ) {
            $this->action = array();
            $this->errors = array();
            $this->image = $this->crop_height = $this->crop_width = $this->resize_height = $this->resize_width = $this->non_prop = NULL;

        }
    }
 

AmdY

Пью пиво
Команда форума
ну вот и строчка которую нужно настраивать, а дальше сам, либо в раздел "работа", а то такие портянки выкладываешь без понимания.
PHP:
imagecopy ( $source, $watermark, ceil(($s_width-$w_width)/2), ceil (($s_height-$w_height)/2), 0, 0, $w_width, $w_height );
 
Сверху