Create a watermark on image

@param PHPThumb $watermarkThumb
@param array $position
@param float $scale
@return Plugins\Watermark
498967
public function createWatermark(PHPThumb $watermarkThumb, array $position = [0, 0], $scale = .5)
    {
        return new Plugins\Watermark($watermarkThumb, $position, $scale);
    }
865108
public function getSubImage(Point $position, Dimensions $size) {
		return new Image(null, $this->image, $position, $size);
	}
387011
private function applyWatermark($imageInstance, $watermark)
    {
        if (!isset($watermark['image'])) {
            $msg = Craft::t('imager', 'Watermark image property not set');
            Craft::error($msg, __METHOD__);
            throw new ImagerException($msg);
        }

        if (!isset($watermark['width'], $watermark['height'])) {
            $msg = Craft::t('imager', 'Watermark image size is not set');
            Craft::error($msg, __METHOD__);
            throw new ImagerException($msg);
        }
        
        if ($this->imagineInstance === null) {
            $msg = Craft::t('imager', 'Imagine instance was not created for driver “{driver}”.', ['driver' => ImagerService::$imageDriver]);
            Craft::error($msg, __METHOD__);
            throw new ImagerException($msg);
        }

        $sourceModel = new LocalSourceImageModel($watermark['image']);
        $sourceModel->getLocalCopy();
        $watermarkInstance = $this->imagineInstance->open($sourceModel->getFilePath());

        try {
            $watermarkBox = new Box($watermark['width'], $watermark['height']);
        } catch (InvalidArgumentException $e) {
            Craft::error($e->getMessage(), __METHOD__);
            throw new ImagerException($e->getMessage(), $e->getCode(), $e);
        }

        $watermarkInstance->resize($watermarkBox, ImageInterface::FILTER_UNDEFINED);

        if (isset($watermark['position'])) {
            $position = $watermark['position'];

            if (isset($position['top'])) {
                $posY = (int)$position['top'];
            } else {
                if (isset($position['bottom'])) {
                    $posY = $imageInstance->getSize()->getHeight() - (int)$watermark['height'] - (int)$position['bottom'];
                } else {
                    $posY = $imageInstance->getSize()->getHeight() - (int)$watermark['height'] - 10;
                }
            }

            if (isset($position['left'])) {
                $posX = (int)$position['left'];
            } else {
                if (isset($position['right'])) {
                    $posX = $imageInstance->getSize()->getWidth() - (int)$watermark['width'] - (int)$position['right'];
                } else {
                    $posX = $imageInstance->getSize()->getWidth() - (int)$watermark['width'] - 10;
                }
            }
        } else {
            $posY = $imageInstance->getSize()->getHeight() - (int)$watermark['height'] - 10;
            $posX = $imageInstance->getSize()->getWidth() - (int)$watermark['width'] - 10;
        }

        try {
            $positionPoint = new Point($posX, $posY);
        } catch (InvalidArgumentException $e) {
            Craft::error($e->getMessage(), __METHOD__);
            throw new ImagerException($e->getMessage(), $e->getCode(), $e);
        }

        if (ImagerService::$imageDriver === 'imagick') {
            /** @var ImagickImage $watermarkInstance */
            $watermarkImagick = $watermarkInstance->getImagick();

            if (isset($watermark['opacity'])) {
                $watermarkImagick->evaluateImage(\Imagick::EVALUATE_MULTIPLY, (float)$watermark['opacity'],
                    \Imagick::CHANNEL_ALPHA);
            }

            if (isset($watermark['blendMode'], ImagerService::$compositeKeyTranslate[$watermark['blendMode']])) {
                $blendMode = ImagerService::$compositeKeyTranslate[$watermark['blendMode']];
            } else {
                $blendMode = \Imagick::COMPOSITE_ATOP;
            }

            /** @var ImagickImage $imageInstance */
            $imageInstance->getImagick()->compositeImage($watermarkImagick, $blendMode, $positionPoint->getX(), $positionPoint->getY());
        } else { // it's GD :(
            try {
                $imageInstance->paste($watermarkInstance, $positionPoint);
            } catch (InvalidArgumentException $e) {
                Craft::error($e->getMessage(), __METHOD__);
                throw new ImagerException($e->getMessage(), $e->getCode(), $e);
            } catch (OutOfBoundsException $e) {
                Craft::error($e->getMessage(), __METHOD__);
                throw new ImagerException($e->getMessage(), $e->getCode(), $e);
            } catch (RuntimeException $e) {
                Craft::error($e->getMessage(), __METHOD__);
                throw new ImagerException($e->getMessage(), $e->getCode(), $e);
            }
        }
    }
217454
protected function do_watermark(\stdClass $src, $watermarkFile) {
		
		if(!file_exists($watermarkFile)) {
			throw new ImageModifierException("Watermark '$watermarkFile' doesn't exist.");
		}
		
		$watermark = new \Imagick($watermarkFile);
		$src->resource->compositeImage($watermark, \Imagick::COMPOSITE_OVER, ($src->width - $watermark->getImageWidth()) / 2, ($src->height - $watermark->getImageHeight()) / 2);
		$src->resource->flattenImages();

		$watermark->clear();

		return $src;
	}
288257
public function addStringWater(Text $text, $position) {

        if ( !$this->imgDst ) return;

        $this->position = $position;

        if ( !$position ) {
            $this->position = self::POS_RANDOM;
        } else {
            $this->position = $position;
        }
        $fontColor = StringUtils::hex2rgb($text->getColor());
        $color = imagecolorallocatealpha($this->imgDst,
            $fontColor['r'],
            $fontColor['g'],
            $fontColor['b'],
            $text->getAlpha());

        $sizeSrc = $this->getImageSize($this->imgDst);
        if ( !file_exists($text->getFont()) ) {
            $text->setFont(dirname(__FILE__).$text->getFont());
        }

        $ttfBox = imagettfbbox($text->getFontsize(), $text->getAngle(), $text->getFont(), $text->getContent());
        $textWidth = $ttfBox[2] - $ttfBox[0];
        $textHeight = abs($ttfBox[7]);
        $waterPosition = $this->getWaterPos($sizeSrc, array($textWidth, $textHeight));
        if ( $this->imgDst ) {
            imagettftext(
                $this->imgDst,
                $text->getFontsize(),
                $this->angle,
                $waterPosition[0],
                $waterPosition[1]+$textHeight,
                $color,
                $text->getFont(),
                $this->getEncodedText($text->getContent()));
        }

        return $this;

    }
437213
public function watermark(ImageResource $watermark, $watermarkPos = 4, $watermarkMargin = 10) {
		switch($watermarkPos) {
			// center
			case 0:
				$watermarkdestX = $this->width/2 - $watermark->getWidth()/2;
				$watermarkdestY = $this->height/2 - $watermark->getHeight()/2;
				break;
				// top left
			case 1:
				$watermarkdestX = $watermarkMargin;
				$watermarkdestY = $watermarkMargin;
				break;
				// top right
			case 2:
				$watermarkdestX = $this->width - $watermark->getWidth() - $watermarkMargin;
				$watermarkdestY = $watermarkMargin;
				break;
				// bottom left
			case 3:
				$watermarkdestX = $watermarkMargin;
				$watermarkdestY = $this->height - $watermark->getHeight() - $watermarkMargin;
				break;
				// bottom right
			case 4:
			default:
				$watermarkdestX = $this->width - $watermark->getWidth() - $watermarkMargin;
				$watermarkdestY = $this->height - $watermark->getHeight() - $watermarkMargin;
				break;
		}

		// set transparency true
		imagealphablending($this->resource, true);
		$watermarkRes = $watermark->getResource();
		imagealphablending($watermarkRes, true);
		imagecopy($this->resource, $watermarkRes, $watermarkdestX, $watermarkdestY, 0, 0, $watermark->getWidth(), $watermark->getHeight());
	}
460976
public function watermark($opacity = 30) 
	{
		// This means that user didn't explicitly call it, use config instead
	    $watermarkInfo = $this->getWatermarkInfo();
		if(null === $watermarkInfo) {
			$this->openWatermark();
		}
		
        // New height and width for the watermark and coords where to place it
        list($resizedWatermarkWidth, $resizedWatermarkHeight, $destX, $destY) = 
        	$this->watermarkDimensionCoords();
        
        // Creation of the temporary watermark for this image
        $watermarkTmpFile = $this->getWatermarkTmpDir() . 
        	"tempWatermark_" . md5(uniqid()) . "." . 
        	$watermarkInfo['extension'];
        
        // This must stay here to ensure that the watermark is the current resource of thumbnailer service
        $this->openWatermark();
        $this->thumbnailerService->resize($resizedWatermarkWidth, $resizedWatermarkHeight);
        $this->thumbnailerService->save($watermarkTmpFile);
        
        // We open the temporary watermark image and the image to watermark using GD libraries
        $watermark = imagecreatefromgif($watermarkTmpFile);
        
        // Creazione del nuovo file immagine
        $imageInfo = $this->getImageInfo();
        switch ($imageInfo['extension']) {
		case 'png':
			$image = @imagecreatefrompng($this->getImageFullPath());
			break;
        
		case 'jpg':
			$image = @imagecreatefromjpeg($this->getImageFullPath());
			break;
        
		case 'gif':
			$image = @imagecreatefromgif($this->getImageFullPath());
			break;
        
		default:
			throw new \RuntimeException('Not supported image type');
			break;
        }
        
        // This is where the watermarking happens
        imagecopymerge(
        	$image, $watermark, $destX, 
        	$destY, 0, 0, $resizedWatermarkWidth, 
        	$resizedWatermarkHeight, $opacity
       	);
        
        switch ($imageInfo['extension']) {
		case 'png':
			$watermarkedImage = @imagepng($image, $this->getImageFullPath(), 0, null); // Corrupted image if NULL fourth parameter omitted!
			break;
        
		case 'jpg':
			$watermarkedImage = @imagejpeg($image, $this->getImageFullPath(), 100);
			break;
        
		case 'gif':
			$watermarkedImage = @imagegif($image, $this->getImageFullPath(), 100);
			break;
        }
        
        // Destruction of the images from memory
        @imagedestroy($watermark);
        @imagedestroy($image);
        
        return $watermarkedImage;
	}
944186
public function stepURL($position)
    {
        $s = 's_'.$position;
        $s = $this->$s;

        return $this->url(null, array('step' => $s));
    }
249597
private BufferedImage create_TICKMARKS_Image(final int WIDTH, final double FREE_AREA_ANGLE,
                                                                final double OFFSET, final double MIN_VALUE,
                                                                final double MAX_VALUE, final double ANGLE_STEP,
                                                                final int TICK_LABEL_PERIOD,
                                                                final int SCALE_DIVIDER_POWER, final boolean DRAW_TICKS,
                                                                final boolean DRAW_TICK_LABELS,
                                                                java.util.ArrayList<Section> tickmarkSections,
                                                                BufferedImage image) {
        if (WIDTH <= 0) {
            return null;
        }
        if (image == null) {
            image = UTIL.createImage(WIDTH, WIDTH, Transparency.TRANSLUCENT);
        }
        final Graphics2D G2 = image.createGraphics();
        G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //G2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        //G2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        //G2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        //G2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        G2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        final int IMAGE_WIDTH = image.getWidth();
        final int IMAGE_HEIGHT = image.getHeight();

        final Font STD_FONT = new Font("Verdana", 0, (int) (0.09 * WIDTH));
        final BasicStroke MEDIUM_STROKE = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
        final BasicStroke THIN_STROKE = new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
        final int TEXT_DISTANCE = (int) (0.17 * WIDTH);
        final int MED_LENGTH = (int) (0.05 * WIDTH);
        final int MAX_LENGTH = (int) (0.07 * WIDTH);

        final Color TEXT_COLOR = super.getBackgroundColor().LABEL_COLOR;
        final Color TICK_COLOR = super.getBackgroundColor().LABEL_COLOR;

        // Create the ticks itself
        final float RADIUS = IMAGE_WIDTH * 0.4f;
        final Point2D ALTIMETER_CENTER = new Point2D.Double(IMAGE_WIDTH / 2.0f, IMAGE_HEIGHT / 2.0f);

        // Draw ticks
        Point2D innerPoint;
        Point2D outerPoint;
        Point2D textPoint = null;
        Line2D tick;
        int counter = 0;
        int tickCounter = 0;

        G2.setFont(STD_FONT);

        double sinValue = 0;
        double cosValue = 0;

        double alpha; // angle for the tickmarks
        final double ALPHA_START = -OFFSET - (FREE_AREA_ANGLE / 2.0);
        float valueCounter; // value for the tickmarks

        for (alpha = ALPHA_START, valueCounter = 0; valueCounter <= 10; alpha -= ANGLE_STEP * 0.1, valueCounter += 0.1) {
            G2.setStroke(THIN_STROKE);
            sinValue = Math.sin(alpha);
            cosValue = Math.cos(alpha);

            // tickmark every 2 units
            if (counter % 2 == 0) {
                G2.setStroke(THIN_STROKE);
                innerPoint = new Point2D.Double(ALTIMETER_CENTER.getX() + (RADIUS - MED_LENGTH) * sinValue, ALTIMETER_CENTER.getY() + (RADIUS - MED_LENGTH) * cosValue);
                outerPoint = new Point2D.Double(ALTIMETER_CENTER.getX() + RADIUS * sinValue, ALTIMETER_CENTER.getY() + RADIUS * cosValue);
                // Draw ticks
                G2.setColor(TICK_COLOR);
                tick = new Line2D.Double(innerPoint.getX(), innerPoint.getY(), outerPoint.getX(), outerPoint.getY());
                G2.draw(tick);
            }

            // Different tickmark every 10 units
            if (counter == 10 || counter == 0) {
                G2.setColor(TEXT_COLOR);
                G2.setStroke(MEDIUM_STROKE);
                innerPoint = new Point2D.Double(ALTIMETER_CENTER.getX() + (RADIUS - MAX_LENGTH) * sinValue, ALTIMETER_CENTER.getY() + (RADIUS - MAX_LENGTH) * cosValue);
                outerPoint = new Point2D.Double(ALTIMETER_CENTER.getX() + RADIUS * sinValue, ALTIMETER_CENTER.getY() + RADIUS * cosValue);
                textPoint = new Point2D.Double(ALTIMETER_CENTER.getX() + (RADIUS - TEXT_DISTANCE + STD_FONT.getSize() / 2f) * sinValue, ALTIMETER_CENTER.getY() + (RADIUS - TEXT_DISTANCE + STD_FONT.getSize() / 2f) * cosValue + TEXT_DISTANCE / 2.5f);

                // Draw text
                final TextLayout TEXT_LAYOUT = new TextLayout(String.valueOf(Math.round(valueCounter)), G2.getFont(), RENDER_CONTEXT);

                final Rectangle2D TEXT_BOUNDARY = TEXT_LAYOUT.getBounds();

                // if gauge is full circle, avoid painting maxValue over minValue
                if (FREE_AREA_ANGLE == 0) {
                    if (Float.compare(valueCounter, 10) != 0) {
                        G2.drawString(String.valueOf(Math.round(valueCounter)), (int) (textPoint.getX() - TEXT_BOUNDARY.getWidth() / 2.0), (int) ((textPoint.getY() - TEXT_BOUNDARY.getHeight() / 2.0)));
                    }
                } else {
                    G2.drawString(String.valueOf(Math.round(valueCounter)), (int) (textPoint.getX() - TEXT_BOUNDARY.getWidth() / 2.0), (int) ((textPoint.getY() - TEXT_BOUNDARY.getHeight() / 2.0)));
                }
                counter = 0;
                tickCounter++;

                // Draw ticks
                G2.setColor(TICK_COLOR);
                tick = new Line2D.Double(innerPoint.getX(), innerPoint.getY(), outerPoint.getX(), outerPoint.getY());
                G2.draw(tick);
            }

            counter++;
        }

        G2.dispose();

        return image;
    }
293340
public function watermark($mark, $pos, $minSize = false) {
        if ($this->file && is_file($mark)) {
            $image     = new \image ($this->file);
            $iw        = intval($image->imagesx());
            $ih        = intval($image->imagesy());
            $watermark = new \image ($mark);
            $w         = 3 * intval($watermark->imagesx());
            $h         = 3 * intval($watermark->imagesy());
            if ($minSize) {
                $minSize = explode('x', $minSize);
                $w       = intval($minSize [0]);
                if (isset ($minSize [1])) {
                    $h = intval($minSize [1]);
                } else {
                    $h = $w;
                }
            }
            if ($iw > $w && $ih > $h) {
                if ($pos == 'rd') {
                    $pos = array_rand(self::$POSITIONS);
                    $pos = self::$POSITIONS [ $pos ];
                    if ($pos == 'mm') {
                        $pos = 'br';
                    }
                }
                $trans = App::cfg('transxy@media');
                if (!preg_match('/^[1-9]\d*x[1-9]\d*$/', $trans)) {
                    $trans = '0x0';
                }
                $image->attach(new \image_draw_watermark ($watermark, $pos, $trans));
                $rst = $image->save($this->file);
                if (!$rst) {
                    log_error('添加水印失败:' . $this->file);

                    return false;
                }
            }
            $image->destroyImage();
        }

        return true;
    }
350312
private function applyWatermarkImagick(Imagick $image)
    {
        $pictureWidth  = $image->getImageWidth();
        $pictureHeight = $image->getImageHeight();

        $watermarkPicture = new Picture($this->watermark, NULL, Picture::WORKER_IMAGICK);

        $opacity = new Opacity($this->opacity);
        $opacity->apply($watermarkPicture);

        if($this->size)
        {
            $resize = new Resize(
                $pictureWidth / 100 * $this->size,
                $pictureHeight / 100 * $this->size,
                Resize::MODE_FIT
            );

            $resize->apply($watermarkPicture);
        }

        $watermark = $watermarkPicture->getResource(Picture::WORKER_IMAGICK);

        $watermarkWidth  = $watermark->getImageWidth();
        $watermarkHeight = $watermark->getImageHeight();

        switch($this->position)
        {
            case 'repeat':

                for($w = 0; $w < $pictureWidth; $w += $watermarkWidth + $this->space)
                {
                    for($h = 0; $h < $pictureHeight; $h += $watermarkHeight + $this->space)
                    {
                        $image->compositeImage($watermark, $watermark->getImageCompose(), $w, $h);
                    }
                }
                return;

            case 'center':

                $positionX = ($image->getImageWidth() - $watermark->getImageWidth()) / 2 - $this->offsetX;
                $positionY = ($image->getImageHeight() - $watermark->getImageHeight()) / 2 - $this->offsetY;
                break;

            case 'topRight':

                $positionX = $image->getImageWidth() - $watermark->getImageWidth() - $this->offsetX;
                $positionY = $this->offsetY;
                break;

            case 'bottomRight':

                $positionX = $image->getImageWidth()  - $watermark->getImageWidth()  - $this->offsetX;
                $positionY = $image->getImageHeight() - $watermark->getImageHeight() - $this->offsetY;
                break;

            case 'bottomLeft':

                $positionX = $this->offsetX;
                $positionY = $image->getImageHeight() - $watermark->getImageHeight() - $this->offsetY;
                break;

            default:

                $positionX = $this->offsetX;
                $positionY = $this->offsetY;
                break;
        }

        $image->compositeImage($watermark, $watermark->getImageCompose(), $positionX, $positionY);
    }
1299368
def watermark
      draw = Magick::Draw.new
      draw.annotate(@canvas, 0, 0, 0, 0, " #{@watermark}") do
        self.fill = 'white'
        text_antialias(false)
        self.font_weight = 100
        self.gravity = Magick::SouthEastGravity
        self.pointsize = 10
        self.undercolor = 'hsla(0,0,0,.5)'
      end
    end
669666
public function watermark(CanvasInterface $watermark, Coordinate $cooridnate = null)
    {
        return $this->apply(new Watermark($watermark, $cooridnate));
    }
882246
protected function watermark($image, $options)
    {
        $watermarkFilename = $options['watermarkFilename'];
        $watermark = Image::getImagine()->open(Yii::getAlias($watermarkFilename));
        $size = $image->getSize();
        $wSize = $watermark->getSize();

        $bottomRight = new Point($size->getWidth() - $wSize->getWidth(), $size->getHeight() - $wSize->getHeight());
        $image->paste($watermark, $bottomRight);

        return $image;
    }
549688
public function watermark($path = null)
    {
        if (is_null($path)) {
            $this->watermarkPath(config('images.watermark_path'));
        }
        $this->watermarkPath($path);
        $this->todo('watermark');

        return $this;
    }
1286696
public function addImageWatermark(Image $image, array $parameters): Image
    {
        $watermark = new Image($this->secret, $parameters['file'], null, $this->autorotate);

        // temporarily enable alphablending to be able to use 32-bit images
        imagealphablending($watermark->getData(), true);
        imagealphablending($image->getData(), true);

        // determine watermark position from config
        if (true === isset($parameters['position'])) {
            $top = intval($parameters['position']['top']) / 100;
            $left = intval($parameters['position']['left']) / 100;
        } else {
            $top = 1;
            $left = 1;
        }

        // determine watermark size from config
        if (true === isset($parameters['size'])) {
            if (self::WATERMARK_SIZE_COVER === $parameters['size']) {
                // cover dimensions are the same as crop dimensions
                $dimensions = $this->getAdjustedImageCropDimensions(
                    $watermark,
                    $image->getWidth(),
                    $image->getHeight(),
                    true
                );
                imagecopyresampled(
                    $image->getData(),
                    $watermark->getData(),
                    0,
                    0,
                    (int)(($watermark->getWidth() - $dimensions['width']) * $left),
                    (int)(($watermark->getHeight() - $dimensions['height']) * $top),
                    $image->getWidth(),
                    $image->getHeight(),
                    $dimensions['width'],
                    $dimensions['height']
                );
            } elseif (self::WATERMARK_SIZE_CONTAIN === $parameters['size']) {
                $dimensions = $this->getAdjustedImageDimensions($watermark, $image->getWidth(), $image->getHeight());
                imagecopyresampled(
                    $image->getData(),
                    $watermark->getData(),
                    (int)(($image->getWidth() - $dimensions['width']) * $left),
                    (int)(($image->getHeight() - $dimensions['height']) * $top),
                    0,
                    0,
                    $dimensions['width'],
                    $dimensions['height'],
                    $watermark->getWidth(),
                    $watermark->getHeight()
                );
            } else {		// percentage
                $dimensions = $this->getAdjustedImageDimensions($watermark, $image->getWidth(), $image->getHeight());
                $dimensions['width'] *= (intval($parameters['size']) / 100);
                $dimensions['height'] *= (intval($parameters['size']) / 100);
                imagecopyresampled(
                    $image->getData(),
                    $watermark->getData(),
                    (int)(($image->getWidth() - $dimensions['width']) * $left),
                    (int)(($image->getHeight() - $dimensions['height']) * $top),
                    0,
                    0,
                    $dimensions['width'],
                    $dimensions['height'],
                    $watermark->getWidth(),
                    $watermark->getHeight()
                );
            }
        } else {
            imagecopy(
                $image->getData(),
                $watermark->getData(),
                (int)(($image->getWidth() - $watermark->getWidth()) * $left),
                (int)(($image->getHeight() - $watermark->getHeight()) * $top),
                0,
                0,
                $watermark->getWidth(),
                $watermark->getHeight()
            );
        }

        // disable alphablending again to be able to save transparency
        imagealphablending($watermark->getData(), false);
        imagealphablending($image->getData(), false);

        return $image;
    }
923529
public String uploadImage(byte[] image, byte[] watermark, String ext, Map<String, String> metaInfo) {
        return uploadImage(image, watermark, ext, metaInfo, DEFAULT_OPACITY, DEFAULT_LOCATION, DEFAULT_MARGIN);
    }