예제 #1
0
 protected function _watermark($filename, $position, $padding = 5)
 {
     extract(parent::_watermark($filename, $position, $padding));
     $wmimage = new \Imagick();
     $wmimage->readImage($filename);
     $wmimage->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $this->config['watermark_alpha'] / 100, \Imagick::CHANNEL_ALPHA);
     $this->imagick->compositeImage($wmimage, \Imagick::COMPOSITE_DEFAULT, $x, $y);
 }
예제 #2
0
        }
        $ctx = stream_context_create($opts);
        // DEBUG
        $debug = fopen('/tmp/maplog', 'a');
        fwrite($debug, $v->{'url'} . ($v->{'grid'} ? '' : "&width={$w}&height={$h}&bbox={$bbox}") . "\n");
        fclose($debug);
        $handle = fopen($tmp_dir . $id . '.png', 'w');
        fwrite($handle, file_get_contents($v->{'url'} . ($v->{'grid'} ? '' : "&width={$w}&height={$h}&bbox={$bbox}"), false, $ctx));
        fclose($handle);
        if (!getimagesize($tmp_dir . $id . '.png')) {
            $img = new Imagick('img/blank.png');
        } else {
            $img = new Imagick($tmp_dir . $id . '.png');
        }
        // leave initially opaque cells alone
        $img->evaluateImage(Imagick::EVALUATE_MULTIPLY, $v->{'opacity'}, Imagick::CHANNEL_ALPHA);
        $canvas->compositeImage($img, imagick::COMPOSITE_OVER, $v->{'x'}, $v->{'y'});
    }
}
foreach ($json->{'legends'} as $k => $v) {
    $handle = fopen($tmp_dir . $id . '.' . count($legends) . '.png', 'w');
    fwrite($handle, @file_get_contents(mkLegendUrl($v)));
    fclose($handle);
    // use a blank image if no real legend came through
    if (!getimagesize($tmp_dir . $id . '.' . count($legends) . '.png')) {
        array_push($legends, new Imagick('img/blank.png'));
    } else {
        array_push($legends, new Imagick($tmp_dir . $id . '.' . count($legends) . '.png'));
    }
    if ($legends[count($legends) - 1]->getImageWidth() > $legSize[0]) {
        $legSize[0] = $legends[count($legends) - 1]->getImageWidth();
예제 #3
0
 /**
  * @param $watermarkImage
  * @param int $positionX
  * @param int $positionY
  * @param int $watermarkImageOpacity
  * @param bool $repeat
  */
 public function watermark($watermarkImage, $positionX = 0, $positionY = 0, $watermarkImageOpacity = 30, $repeat = false)
 {
     Varien_Profiler::start(__METHOD__);
     /** @var $watermark Imagick */
     $watermark = new Imagick($watermarkImage);
     //better method to blow up small images.
     $watermark->setimageinterpolatemethod(Imagick::INTERPOLATE_NEARESTNEIGHBOR);
     if ($this->_watermarkImageOpacity == null) {
         $opc = $watermarkImageOpacity;
     } else {
         $opc = $this->getWatermarkImageOpacity();
     }
     $watermark->evaluateImage(Imagick::EVALUATE_MULTIPLY, $opc, Imagick::CHANNEL_ALPHA);
     // how big are the images?
     $iWidth = $this->getImageMagick()->getImageWidth();
     $iHeight = $this->getImageMagick()->getImageHeight();
     //resize watermark to configuration size
     if ($this->getWatermarkWidth() && $this->getWatermarkHeigth() && $this->getWatermarkPosition() != self::POSITION_STRETCH) {
         $watermark->scaleImage($this->getWatermarkWidth(), $this->getWatermarkHeigth());
     }
     // get watermark size
     $wWidth = $watermark->getImageWidth();
     $wHeight = $watermark->getImageHeight();
     //check if watermark is still bigger then image.
     if ($iHeight < $wHeight || $iWidth < $wWidth) {
         // resize the watermark
         $watermark->scaleImage($iWidth, $iHeight);
         // get new size
         $wWidth = $watermark->getImageWidth();
         $wHeight = $watermark->getImageHeight();
     }
     $x = 0;
     $y = 0;
     switch ($this->getWatermarkPosition()) {
         case self::POSITION_CENTER:
             $x = ($iWidth - $wWidth) / 2;
             $y = ($iHeight - $wHeight) / 2;
             break;
         case self::POSITION_STRETCH:
             $watermark->scaleimage($iWidth, $iHeight);
             break;
         case self::POSITION_TOP_RIGHT:
             $x = $iWidth - $wWidth;
             break;
         case self::POSITION_BOTTOM_LEFT:
             $y = $iHeight - $wHeight;
             break;
         case self::POSITION_BOTTOM_RIGHT:
             $x = $iWidth - $wWidth;
             $y = $iHeight - $wHeight;
             break;
         default:
             break;
     }
     $this->getImageMagick()->compositeImage($watermark, Imagick::COMPOSITE_OVER, $x, $y);
     $watermark->clear();
     $watermark->destroy();
     Varien_Profiler::stop(__METHOD__);
 }
예제 #4
0
include_once 'config.php';
include_once 'functions.php';
if (isPost()) {
    // Get post parameters
    $originX = post('originX');
    $originY = post('originY');
    $transparency = post('transparency');
    $watermarkResize = post('markMin');
    $originalImagePath = post('originalImage');
    $watermarkImagePath = post('watermarkImage');
    // Open images
    $original = new Imagick($originalImagePath);
    $watermark = new Imagick($watermarkImagePath);
    // Set opacity for images with alpha channel and without
    if ($watermark->getImageAlphaChannel()) {
        $watermark->evaluateImage(Imagick::EVALUATE_DIVIDE, 1.0 / $transparency, Imagick::CHANNEL_ALPHA);
    } else {
        $watermark->setImageOpacity($transparency);
    }
    // Resize image
    if ($watermarkResize > 1) {
        $watermark->resizeImage($watermark->getImageWidth() / $watermarkResize, $watermark->getImageHeight() / $watermarkResize, Imagick::FILTER_LANCZOS, 1);
    }
    // Watermark block
    $isPattern = post('isPattern');
    if (bool($isPattern)) {
        // Get watermark`s offset from original image
        $initialX = (int) str_replace('px', '', post('x'));
        $initialY = (int) str_replace('px', '', post('y'));
        // Get watermark sizes
        $watermarkWidth = $watermark->getImageWidth();
예제 #5
0
 /**
  * Fill the image background.
  * @param integer $r
  * @param integer $g
  * @param integer $b
  * @param integer $opacity
  */
 protected function _background($r, $g, $b, $opacity)
 {
     $background = new \Imagick();
     $background->newImage($this->width, $this->height, new \ImagickPixel(sprintf('rgb(%d, %d, %d)', $r, $g, $b)));
     if (!$background->getImageAlphaChannel()) {
         $background->setImageAlphaChannel(\Imagick::ALPHACHANNEL_SET);
     }
     $background->setImageBackgroundColor(new \ImagickPixel('transparent'));
     $background->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $opacity / 100, \Imagick::CHANNEL_ALPHA);
     $background->setColorspace($this->im->getColorspace());
     if ($background->compositeImage($this->im, \Imagick::COMPOSITE_DISSOLVE, 0, 0)) {
         $this->im = $background;
     }
 }
예제 #6
0
 /**
  * @param string $image
  * @param int $x
  * @param int $y
  * @param int $alpha
  * @return Pimcore_Image_Adapter_Imagick
  */
 public function addOverlay($image, $x = 0, $y = 0, $alpha = null, $composite = "COMPOSITE_DEFAULT")
 {
     $image = ltrim($image, "/");
     $image = PIMCORE_DOCUMENT_ROOT . "/" . $image;
     // 100 alpha is default
     if (empty($alpha)) {
         $alpha = 100;
     }
     $alpha = round($alpha / 100, 1);
     if (is_file($image)) {
         $newImage = new Imagick();
         $newImage->readimage($image);
         $newImage->evaluateImage(Imagick::EVALUATE_MULTIPLY, $alpha, Imagick::CHANNEL_ALPHA);
         $this->resource->compositeImage($newImage, constant("Imagick::" . $composite), $x, $y);
     }
     $this->reinitializeImage();
     return $this;
 }
예제 #7
0
 /**
  * @param array $options
  *     'watermark' => waImage|string $watermark
  *     'opacity' => float|int 0..1
  *     'align' => self::ALIGN_* const
  *     'font_file' => null|string If null - will be used some default font. Note: use when watermark option is text
  *     'font_size' => float Size of font. Note: use when watermark option is text
  *     'font_color' => string Hex-formatted of color (without #). Note: use when watermark option is text
  *     'text_orientation' => self::ORIENTATION_* const. Note: use when watermark option is text
  * @return mixed
  */
 protected function _watermark($options)
 {
     // export options to php-vars
     foreach ($options as $name => $value) {
         ${$name} = $value;
     }
     $opacity = min(max($opacity, 0), 1);
     /**
      * @var waImage $watermark
      */
     if ($watermark instanceof waImage) {
         $offset = $this->calcWatermarkOffset($watermark->width, $watermark->height, $align);
         $watermark = new Imagick($watermark->file);
         $watermark->evaluateImage(Imagick::EVALUATE_MULTIPLY, $opacity, Imagick::CHANNEL_ALPHA);
         $this->im->compositeImage($watermark, Imagick::COMPOSITE_DEFAULT, $offset[0], $offset[1]);
         $watermark->clear();
         $watermark->destroy();
     } else {
         $text = (string) $watermark;
         if (!$text) {
             return;
         }
         $font_size = 24 * $font_size / 18;
         // 24px = 18pt
         $font_color = new ImagickPixel('#' . $font_color);
         $watermark = new ImagickDraw();
         $watermark->setFillColor($font_color);
         $watermark->setFillOpacity($opacity);
         if ($font_file && file_exists($font_file)) {
             $watermark->setFont($font_file);
         }
         $watermark->setFontSize($font_size);
         // Throws ImagickException on error
         $metrics = $this->im->queryFontMetrics($watermark, $text);
         $width = $metrics['textWidth'];
         $height = $metrics['textHeight'];
         if ($text_orientation == self::ORIENTATION_VERTICAL) {
             list($width, $height) = array($height, $width);
         }
         $offset = $this->calcWatermarkTextOffset($width, $height, $align, $text_orientation);
         $this->im->annotateImage($watermark, $offset[0], $offset[1], $text_orientation == self::ORIENTATION_VERTICAL ? -90 : 0, $text);
         $watermark->clear();
         $watermark->destroy();
     }
 }
예제 #8
0
 public function writeWatermarkIm($opacity = 50, $marginH = 0, $marginV = 0, $positionWatermarkLeftRight = 'c', $positionWatermarkTopBottom = 'c')
 {
     //add Watermark
     list($imageCreateFunc, $imageSaveFunc) = $this->_watermark->_getFunctionNames();
     $watermarkImage = $imageCreateFunc($this->_watermark->_getImage());
     //get base image
     list($imageCreateFunc, $imageSaveFunc) = $this->_getFunctionNames();
     $baseImage = @$imageCreateFunc($this->_image);
     if (!$baseImage) {
         return false;
     }
     //Calculate margins
     if ($positionWatermarkLeftRight == 'r') {
         $marginH = imagesx($baseImage) - imagesx($watermarkImage) - $marginH;
     }
     if ($positionWatermarkLeftRight == 'c') {
         $marginH = imagesx($baseImage) / 2 - imagesx($watermarkImage) / 2 - $marginH;
     }
     if ($positionWatermarkTopBottom == 'b') {
         $marginV = imagesy($baseImage) - imagesy($watermarkImage) - $marginV;
     }
     if ($positionWatermarkTopBottom == 'c') {
         $marginV = imagesy($baseImage) / 2 - imagesy($watermarkImage) / 2 - $marginV;
     }
     $image = new Imagick($this->_image);
     $image->coalesceimages();
     $watermark = new Imagick();
     $watermark->readimage($this->_watermark->_getImage());
     $watermark->evaluateImage(Imagick::EVALUATE_DIVIDE, 100 / $opacity, Imagick::CHANNEL_ALPHA);
     if ($imageSaveFunc == 'ImageGIF') {
         if (XenForo_Application::getOptions()->xengalleryWatermarkAnimated) {
             try {
                 foreach ($image as $frame) {
                     $frame->compositeImage($watermark, imagick::COMPOSITE_OVER, $marginH, $marginV);
                 }
                 if (!$image->writeimages($this->tmpFile, true)) {
                     throw new Exception('Cannot save file ' . $this->tmpFile);
                 }
             } catch (Exception $e) {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         $image->compositeImage($watermark, imagick::COMPOSITE_OVER, $marginH, $marginV);
         if (!$image->writeimage($this->tmpFile)) {
             throw new Exception('Cannot save file ' . $this->tmpFile);
         }
     }
     //Set new main image
     $this->_setNewMainImage($this->tmpFile);
     $image->destroy();
     $watermark->destroy();
     return true;
 }
예제 #9
0
 /**
  * Создание превью средствами imagick
  * @param $src_file исходный файл
  * @param $dst_file файл с результатом
  * @param max_w максимальная ширина
  * @param max_h максимальная высота
  * @return bool
  */
 private function image_constrain_imagick($src_file, $dst_file, $max_w, $max_h, $watermark = null, $watermark_offet_x = 0, $watermark_offet_y = 0, $watermark_opacity = 1, $sharpen = 0.2)
 {
     $thumb = new Imagick();
     // Читаем изображение
     if (!$thumb->readImage($src_file)) {
         return false;
     }
     // Размеры исходного изображения
     $src_w = $thumb->getImageWidth();
     $src_h = $thumb->getImageHeight();
     // Нужно ли обрезать?
     if (!$watermark && $src_w <= $max_w && $src_h <= $max_h) {
         // Нет - просто скопируем файл
         if (!copy($src_file, $dst_file)) {
             return false;
         }
         return true;
     }
     // Размеры превью при пропорциональном уменьшении
     list($dst_w, $dst_h) = $this->calc_contrain_size($src_w, $src_h, $max_w, $max_h);
     // Уменьшаем
     $thumb->thumbnailImage($dst_w, $dst_h);
     // Устанавливаем водяной знак
     if ($watermark && is_readable($watermark)) {
         $overlay = new Imagick($watermark);
         //$overlay->setImageOpacity($watermark_opacity);
         //$overlay_compose = $overlay->getImageCompose();
         $overlay->evaluateImage(Imagick::EVALUATE_MULTIPLY, $watermark_opacity, Imagick::CHANNEL_ALPHA);
         // Get the size of overlay
         $owidth = $overlay->getImageWidth();
         $oheight = $overlay->getImageHeight();
         $watermark_x = min(($dst_w - $owidth) * $watermark_offet_x / 100, $dst_w);
         $watermark_y = min(($dst_h - $oheight) * $watermark_offet_y / 100, $dst_h);
     }
     // Анимированные gif требуют прохода по фреймам
     foreach ($thumb as $frame) {
         // Уменьшаем
         $frame->thumbnailImage($dst_w, $dst_h);
         /* Set the virtual canvas to correct size */
         $frame->setImagePage($dst_w, $dst_h, 0, 0);
         // Наводим резкость
         if ($sharpen > 0) {
             $thumb->adaptiveSharpenImage($sharpen, $sharpen);
         }
         if (isset($overlay) && is_object($overlay)) {
             // $frame->compositeImage($overlay, $overlay_compose, $watermark_x, $watermark_y, imagick::COLOR_ALPHA);
             $frame->compositeImage($overlay, imagick::COMPOSITE_OVER, $watermark_x, $watermark_y, imagick::COLOR_ALPHA);
         }
     }
     // Убираем комменты и т.п. из картинки
     $thumb->stripImage();
     //		$thumb->setImageCompressionQuality(100);
     // Записываем картинку
     if (!$thumb->writeImages($dst_file, true)) {
         return false;
     }
     // Уборка
     $thumb->destroy();
     if (isset($overlay) && is_object($overlay)) {
         $overlay->destroy();
     }
     return true;
 }
예제 #10
0
 /**
  * @see	\wcf\system\image\adapter\IImageAdapter::overlayImage()
  */
 public function overlayImage($file, $x, $y, $opacity)
 {
     try {
         $overlayImage = new \Imagick($file);
     } catch (\ImagickException $e) {
         throw new SystemException("Image '" . $file . "' is not readable or does not exist.");
     }
     $overlayImage->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $opacity, \Imagick::CHANNEL_OPACITY);
     if ($this->imagick->getImageFormat() == 'GIF') {
         $this->imagick = $this->imagick->coalesceImages();
         do {
             $this->imagick->compositeImage($overlayImage, \Imagick::COMPOSITE_OVER, $x, $y);
         } while ($this->imagick->nextImage());
     } else {
         $this->imagick->compositeImage($overlayImage, \Imagick::COMPOSITE_OVER, $x, $y);
         $this->imagick = $this->imagick->flattenImages();
     }
 }
예제 #11
0
파일: imagick.php 프로젝트: adjaika/J3Base
 public function watermark($options)
 {
     // Make sure the resource handle is valid.
     if (!$this->isLoaded()) {
         throw new LogicException('No valid image was loaded.');
     }
     if ($options->opacity > 1) {
         $options->opacity = $options->opacity / 100;
     }
     if ($options->type == 'text') {
         if (isset($options->text)) {
             $this->watermarkText($options);
         }
     } else {
         if (isset($options->image)) {
             $watermark = new Imagick($options->image);
             $width = $this->getWidth();
             $height = $this->getHeight();
             $mw = $watermark->getImageWidth();
             $mh = $watermark->getImageHeight();
             switch ($options->position) {
                 default:
                 case 'center':
                     $x = floor(($width - $mw) / 2);
                     $y = floor(($height - $mh) / 2);
                     break;
                 case 'top-left':
                     $x = $options->margin;
                     $y = floor($mh / 2) + $options->margin;
                     break;
                 case 'top-right':
                     $x = $width - $mw - $options->margin;
                     $y = floor($mh / 2) + $options->margin;
                     break;
                 case 'center-left':
                     $x = 0 + $options->margin;
                     $y = floor(($height - $mh) / 2);
                     break;
                 case 'center-right':
                     $x = $width - $mw - $options->margin;
                     $y = floor(($height - $mh) / 2);
                     break;
                 case 'top-center':
                     $x = floor(($width - $mw) / 2);
                     $y = floor($mh / 2) + $options->margin;
                     break;
                 case 'bottom-center':
                     $x = floor(($width - $mw) / 2);
                     $y = $height - $mh - $options->margin;
                     break;
                 case 'bottom-left':
                     $x = 0 + $options->margin;
                     $y = $height - $mh - $options->margin;
                     break;
                 case 'bottom-right':
                     $x = $width - $mw - $options->margin;
                     $y = $height - $mh - $options->margin;
                     break;
             }
             if ($watermark->getImageFormat() == 'PNG') {
                 $watermark->evaluateImage(Imagick::EVALUATE_MULTIPLY, (double) $options->opacity, Imagick::CHANNEL_ALPHA);
             } else {
                 $watermark->setImageOpacity((double) $options->opacity);
             }
             $this->handle->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y);
         }
     }
     return $this;
 }
예제 #12
0
파일: Images.php 프로젝트: difra-org/difra
 /**
  * Add watermark (text or image)
  * @param string $image
  * @param string $text
  * @param string $watermarkImage
  * @param string $type
  * @param int $padding
  * @param float|int $opacity
  * @return string
  */
 public static function setWatermark($image, $text = null, $watermarkImage = null, $type = 'png', $padding = 0, $opacity = 0.5)
 {
     if (is_null($text) && is_null($watermarkImage) || $text != '' && $watermarkImage != '') {
         return $image;
     }
     $originalImage = self::data2image($image);
     if (!is_null($watermarkImage) && $watermarkImage != '') {
         $watermarkImage = self::data2image($watermarkImage);
     }
     if (!is_null($text) && $text !== '') {
         // text watermark
         $watermarkImage = new \Imagick();
         $draw = new \ImagickDraw();
         $draw->setFont(DIR_FW . 'lib/libs/capcha/DejaVuSans.ttf');
         $draw->setFontSize(10);
         $draw->setGravity(\imagick::GRAVITY_CENTER);
         $textDArray = $watermarkImage->queryfontmetrics($draw, $text);
         $watermarkImage->newImage($textDArray['textWidth'] + 7, $textDArray['textHeight'] + 1, new \ImagickPixel('none'));
         $watermarkImage->setImageFormat('png');
     }
     // create watermark
     $image_width = $originalImage->getImageWidth();
     $image_height = $originalImage->getImageHeight();
     $watermark_width = $watermarkImage->getImageWidth();
     $watermark_height = $watermarkImage->getImageHeight();
     // verify if watermark fits image
     if ($image_width < $watermark_width + $padding || $image_height < $watermark_height + $padding) {
         return self::image2data($originalImage, $type);
     }
     // define watermark position
     $positions = [];
     $positions[] = [0 + $padding, 0 + $padding];
     $positions[] = [$image_width - $watermark_width - $padding, 0 + $padding];
     $positions[] = [$image_width - $watermark_width - $padding, $image_height - $watermark_height - $padding];
     $positions[] = [0 + $padding, $image_height - $watermark_height - $padding];
     $min = null;
     $min_colors = 0;
     $textColor = 'black';
     foreach ($positions as $position) {
         $colors = $originalImage->getImageRegion($watermark_width, $watermark_height, $position[0], $position[1])->getImageColors();
         if ($min === null || $colors <= $min_colors) {
             $min = $position;
             $min_colors = $colors;
         }
     }
     $region = $originalImage->getImageRegion($watermark_width, $watermark_height, $min[0], $min[1]);
     $region->scaleImage(1, 1);
     $aColor = $region->getImagePixelColor(1, 1)->getColor();
     $colorSum = $aColor['r'] + $aColor['g'] + $aColor['b'];
     if ($colorSum < 390) {
         $textColor = 'white';
     }
     if (!is_null($text) && $text !== '') {
         $draw->setFillColor(new \ImagickPixel($textColor));
         $draw->setFillOpacity($opacity);
         $watermarkImage->annotateimage($draw, 0, 0, 0, $text);
     } else {
         $watermarkImage->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $opacity, \Imagick::CHANNEL_ALPHA);
         //$watermarkImage->setImageOpacity( $opacity );
     }
     // Put watermark
     $originalImage->compositeImage($watermarkImage, \Imagick::COMPOSITE_OVER, $min[0], $min[1]);
     return self::image2data($originalImage, $type);
 }
예제 #13
0
 protected function _background($r, $g, $b, $opacity)
 {
     $color = sprintf("rgb(%d, %d, %d)", $r, $g, $b);
     $pixel1 = new \ImagickPixel($color);
     $opacity = $opacity / 100;
     $pixel2 = new \ImagickPixel("transparent");
     $background = new \Imagick();
     $this->_image->setIteratorIndex(0);
     while (true) {
         $background->newImage($this->_width, $this->_height, $pixel1);
         if (!$background->getImageAlphaChannel()) {
             $background->setImageAlphaChannel(constant("Imagick::ALPHACHANNEL_SET"));
         }
         $background->setImageBackgroundColor($pixel2);
         $background->evaluateImage(constant("Imagick::EVALUATE_MULTIPLY"), $opacity, constant("Imagick::CHANNEL_ALPHA"));
         $background->setColorspace($this->_image->getColorspace());
         $background->compositeImage($this->_image, constant("Imagick::COMPOSITE_DISSOLVE"), 0, 0);
         if (!$this->_image->nextImage()) {
             break;
         }
     }
     $this->_image->clear();
     $this->_image->destroy();
     $this->_image = $background;
 }
예제 #14
0
 /**
  * 图片合成,可以进行多张图片的合成,也可以做图片水印用
  * <pre>
  * 注意composite方法在和其它图片处理方法一起使用时,composite必须第一个被调用
  * 在图片合成时,初始化对象传递imageData数据需要是一个二维数组。
  * </pre>
  * 数组中的每个成员也是数组,需要包含5个元素:
  * - 表示图像数据的blob字符串 (blob string)
  * - 表示在画布上放置图像时相对锚点位置的 x 偏移的像素数(可能为负)
  * - 表示在画布上放置图像时相对锚点位置的 y 偏移的像素数(可能为负)
  * - 表示图像不透明度(opacity)的浮点数,在 0.0 至 1.0 之间(包括 0.0 和 1.0)0表示全透明,1表示最不透明。
  * - 画布上锚点的位置,是以下之一:
  * <pre>
  *	 SAE_TOP_LEFT SAE_TOP_CENTER SAE_TOP_RIGHT SAE_CENTER_LEFT SAE_CENTER_CENTER
  *	 SAE_CENTER_RIGHT SAE_BOTTOM_LEFT SAE_BOTTOM_CENTER SAE_BOTTOM_RIGHT
  * </pre>
  * 注意上面的x偏移和y偏移,和锚点位置有关,如果选择了锚点TOP_RIGHT,<br>
  * 则x和y的偏移是指该图片的TOP_RIGHT(右上角)相对于画布的右上角的偏移;<br>
  * 但如果选择BOTTOM_LEFT(左下角)为锚点,则x/y偏移就是指该图片的左下角<br>
  * 相对于画布的左下角的偏移量。<br>
  * <b>偏移的正负同数学中的象限规定。</b><br>
  * 图片的放置顺序同数组中出现的顺序
  *
  * <code>
  * <?php
  * //从网络上抓取要合成的多张图片
  * $img1 = file_get_contents('http://ss2.sinaimg.cn/bmiddle/53b05ae9t73817f6bf751&690');
  * $img2 = file_get_contents('http://timg.sjs.sinajs.cn/miniblog2style/images/common/logo.png');
  * $img3 = file_get_contents('http://i1.sinaimg.cn/home/deco/2009/0330/logo_home.gif');
  *
  * //实例化SaeImage并取得最大一张图片的大小,稍后用于设定合成后图片的画布大小
  * $img = new SaeImage( $img1 );
  * $size = $img->getImageAttr();
  *
  * //清空$img数据
  * $img->clean();
  *
  * //设定要用于合成的三张图片(如果重叠,排在后面的图片会盖住排在前面的图片)
  * $img->setData( array(
  * array( $img1, 0, 0, 1, SAE_TOP_LEFT ),
  * array( $img2, 0, 0, 0.5, SAE_BOTTOM_RIGHT ),
  * array( $img3, 0, 0, 1, SAE_BOTTOM_LEFT ),
  * ) );
  *
  * //执行合成
  * $img->composite($size[0], $size[1]);
  *
  * //输出图片
  * $img->exec('jpg', true);
  * ?>
  * </code>
  * @param int $width 设置画布宽度
  * @param int $height 设置画布高度
  * @param string $color 设置画布颜色
  * @return bool
  * @author Sauwe
  */
 public function composite($width, $height, $color = "black")
 {
     if ($this->notValid()) {
         return false;
     }
     $width = intval($width);
     $height = intval($height);
     try {
         $im = new Imagick();
         $im->newImage($width, $height, new ImagickPixel($color));
         $im->setImageFormat('jpg');
         foreach ($this->_img_data as $img) {
             $data = $img[0];
             $x = $img[1];
             $y = $img[2];
             $opacity = $img[3];
             $anchor = $img[4];
             if (!method_exists($this, $anchor)) {
                 continue;
             }
             $imgc = new Imagick();
             $imgc->readImageBlob($data);
             $sw = $imgc->getImageWidth();
             $sh = $imgc->getImageHeight();
             $offset = $this->{$anchor}($width, $height, $sw, $sh, $x, $y);
             if ($opacity == 0) {
                 continue;
             }
             $imgc->evaluateImage(Imagick::EVALUATE_DIVIDE, 1 / $opacity, Imagick::CHANNEL_ALPHA);
             $im->compositeImage($imgc, Imagick::COMPOSITE_DEFAULT, $offset[0], $offset[1]);
         }
         $this->_img_data = $im->getImageBlob();
         return true;
     } catch (Exception $e) {
         $this->_errno = SAE_ErrUnknown;
         $this->_errmsg = $e->getMessage();
         return false;
     }
 }
예제 #15
0
파일: imagick.php 프로젝트: MenZil-Team/cms
 protected function _do_background($r, $g, $b, $opacity)
 {
     // Create a RGB color for the background
     $color = sprintf('rgb(%d, %d, %d)', $r, $g, $b);
     // Create a new image for the background
     $background = new Imagick();
     $background->newImage($this->width, $this->height, new ImagickPixel($color));
     if (!$background->getImageAlphaChannel()) {
         // Force the image to have an alpha channel
         $background->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET);
     }
     // Clear the background image
     $background->setImageBackgroundColor(new ImagickPixel('transparent'));
     // NOTE: Using setImageOpacity will destroy current alpha channels!
     $background->evaluateImage(Imagick::EVALUATE_MULTIPLY, $opacity / 100, Imagick::CHANNEL_ALPHA);
     // Match the colorspace between the two images before compositing
     $background->setColorspace($this->im->getColorspace());
     if ($background->compositeImage($this->im, Imagick::COMPOSITE_DISSOLVE, 0, 0)) {
         // Replace the current image with the new image
         $this->im = $background;
         return TRUE;
     }
     return FALSE;
 }
예제 #16
0
    public static function addWatermark($src_img, $wm_img, $pos='rb', $q=80) {
        if ($wm_img === false) {
            $wm_img = cmsConfig::getInstance()->wmark;
        }
        
        if (!$src_img || !$wm_img) { return false; }
        
        $size_src = self::getImgInfo($src_img);
        $size_wm  = self::getImgInfo($wm_img);
        
        if (!$size_src || !$size_wm) { return false; }
        
        if (self::checkImagick() === true) {
            $image = new Imagick($src_img);
            $wm    = new Imagick($wm_img);
            
            $wm->scaleImage($size_src['width']/10, 0);
            
            list($X, $Y) = $this->getWatermarkPos($size_src['width'], $size_src['height'], $wm->getImageWidth(), $wm->getImageHeight());
            if ($X < 0 || $Y < 0) { return false; }
            
            $wm->evaluateImage(Imagick::EVALUATE_MULTIPLY, 0.8, Imagick::CHANNEL_ALPHA);
            
            if ($size_src == 'gif') {
                foreach ($image as $img) {
                    $img->compositeImage($wm, imagick::COMPOSITE_OVER, $X, $Y);
                }
                
                $image->writeimages($src_img);
            } else {
                $image->compositeImage($wm, imagick::COMPOSITE_OVER, $X, $Y);
                $image->writeimage($src_img);
            }
            
            $image->destroy();
            $wm->destroy();
        } else {
            $wimage = imagecreatefrompng($wm_img);
            if ($size_wm['type'] != 'png' || empty($wimage)) { return false; }

            list($X, $Y) = $this->getWatermarkPos($size_src['width'], $size_src['height'], $size_wm['width'], $size_wm['height']);
            if ($X < 0 || $Y < 0) { return false; }

            switch($size_src['type']) {
                case 'jpg':
                    $image = imagecreatefromjpeg($src_img);
                    break;
                case 'gif':
                    $image = imagecreatefromgif($src_img);
                    break;
                case 'png':
                    $image = imagecreatefrompng($src_img);
                    break;
                default: break;
            }

            if (!$image) { return false; }

            imagecopyresampled($image, $wimage, $X, $Y, 0, 0, $size_wm['width'], $size_wm['height'], $size_wm['width'], $size_wm['height']);

            switch($size_src['type']) {
                case 'jpg':
                    imagejpeg($image, $src_img, $q);
                    break;
                case 'gif':
                    imagegif($image, $src_img);
                    break;
                case 'png':
                    imagepng($image, $src_img, (9 - round($q*0.09)));
                    break;
            }

            imagedestroy($image);
            imagedestroy($wimage);
        }
        
        return true;
    }
 private function _mergeSingleImg($margedImagePath)
 {
     switch ($this->imageProcessLib) {
         case 'gd':
             $watermarkInfo = getimagesize($this->watermarkPath);
             if ($watermarkInfo["mime"] == "image/png") {
                 $watermark = imagecreatefrompng($this->watermarkPath);
             } else {
                 $watermark = imagecreatefromjpeg($this->watermarkPath);
             }
             $imageInfo = getimagesize($this->imagePath);
             if ($imageInfo["mime"] == "image/png") {
                 $image = imagecreatefrompng($this->imagePath);
             } else {
                 $image = imagecreatefromjpeg($this->imagePath);
             }
             imagesavealpha($image, true);
             imagesavealpha($watermark, true);
             imagealphablending($image, false);
             imagealphablending($watermark, false);
             if ($watermarkInfo[0] > $imageInfo[0] || $watermarkInfo[1] > $imageInfo[1]) {
                 $kWidth = $watermarkInfo[0] / $imageInfo[0];
                 $kHeight = $watermarkInfo[0] / $imageInfo[0];
                 if ($kWidth > $kHeight) {
                     // Масштабируем по ширине
                     $watermarkInfo[0] = $watermarkInfo[0] / $kWidth;
                     $watermarkInfo[1] = $watermarkInfo[1] / $kWidth;
                 } else {
                     // Масштабируем по высоте
                     $watermarkInfo[0] = $watermarkInfo[0] / $kHeight;
                     $watermarkInfo[1] = $watermarkInfo[1] / $kHeight;
                 }
                 imagecopyresampled($watermark, $watermark, 0, 0, 0, 0, $watermarkInfo[0], $watermarkInfo[1], imagesx($watermark), imagesy($watermark));
             }
             imagecopy($image, $watermark, $this->watermarkOfsetX, $this->watermarkOfsetY, 0, 0, $watermarkInfo[0], $watermarkInfo[1]);
             if ($imageInfo["mime"] == "image/png") {
                 imagepng($image, $margedImagePath);
             } else {
                 imagejpeg($image, $margedImagePath);
             }
             imagedestroy($image);
             imagedestroy($watermark);
             break;
         case 'imagick':
             $image = new Imagick();
             $image->readImage($this->imagePath);
             $watermark = new Imagick();
             $watermark->readImage($this->watermarkPath);
             if (!$watermark->getImageAlphaChannel()) {
                 $watermark->setImageAlphaChannel(1);
             }
             if ($watermark->getImageWidth() > $image->getImageWidth() || $watermark->getImageHeight() > $image->getImageHeight()) {
                 $kWidth = $watermark->getImageWidth() / $image->getImageWidth();
                 $kHeight = $watermark->getImageHeight() / $image->getImageHeight();
                 if ($kWidth > $kHeight) {
                     // Масштабируем по ширине
                     $watermark->scaleImage($watermark->getImageWidth() / $kWidth, $watermark->getImageHeight() / $kWidth);
                 } else {
                     // Масштабируем по высоте
                     $watermark->scaleImage($watermark->getImageWidth() / $kHeight, $watermark->getImageHeight() / $kHeight);
                 }
             }
             $watermark->evaluateImage(Imagick::EVALUATE_MULTIPLY, $this->watermarkTransparency, Imagick::CHANNEL_ALPHA);
             $image->compositeImage($watermark, imagick::COMPOSITE_OVER, $this->watermarkOfsetX, $this->watermarkOfsetY);
             $image->writeImage($margedImagePath);
             break;
         default:
             echo json_encode(array('status' => 'error', 'errorId' => '1-6', 'errorText' => 'An invalid image processing library'), JSON_FORCE_OBJECT);
             exit;
             break;
     }
     return true;
 }