Adds a watermark to an image
344198
def watermark(img, mark, position=(0, 0), opacity=1, scale=1.0, tile=False,
              greyscale=False, rotation=0, return_name=False, **kwargs):
    """"""

    if opacity < 1:
        mark = reduce_opacity(mark, opacity)

    if not isinstance(scale, tuple):
        scale = determine_scale(scale, img, mark)

    mark = mark.resize(scale, resample=Image.ANTIALIAS)

    if greyscale and mark.mode != 'LA':
        mark = mark.convert('LA')

    rotation = determine_rotation(rotation, mark)
    if rotation != 0:
        # give some leeway for rotation overlapping
        new_w = int(mark.size[0] * 1.5)
        new_h = int(mark.size[1] * 1.5)

        new_mark = Image.new('RGBA', (new_w, new_h), (0,0,0,0))

        # center the watermark in the newly resized image
        new_l = int((new_w - mark.size[0]) / 2)
        new_t = int((new_h - mark.size[1]) / 2)
        new_mark.paste(mark, (new_l, new_t))

        mark = new_mark.rotate(rotation)

    position = determine_position(position, img, mark)

    if img.mode != 'RGBA':
        img = img.convert('RGBA')

    # make sure we have a tuple for a position now
    assert isinstance(position, tuple), 'Invalid position "%s"!' % position

    # create a transparent layer the size of the image and draw the
    # watermark in that layer.
    layer = Image.new('RGBA', img.size, (0,0,0,0))
    if tile:
        first_y = int(position[1] % mark.size[1] - mark.size[1])
        first_x = int(position[0] % mark.size[0] - mark.size[0])

        for y in range(first_y, img.size[1], mark.size[1]):
            for x in range(first_x, img.size[0], mark.size[0]):
                layer.paste(mark, (x, y))
    else:
        layer.paste(mark, position)

    # composite the watermark with the layer
    return Image.composite(layer, img, layer)
97418
def watermark(url, args=''):
    
    # initialize some variables
    args = args.split(',')

    params = dict(
        name=args.pop(0),
        opacity=0.5,
        tile=False,
        scale=1.0,
        greyscale=False,
        rotation=0,
        position=None,
        quality=QUALITY,
        obscure=OBSCURE_ORIGINAL,
        random_position_once=RANDOM_POSITION_ONCE,
    )

    params['url'] = unquote(url)

    # iterate over all parameters to see what we need to do
    for arg in args:
        key, value = arg.split('=')
        key, value = key.strip(), value.strip()
        if key == 'position':
            params['position'] = value
        elif key == 'opacity':
            params['opacity'] = utils._percent(value)
        elif key == 'tile':
            params['tile'] = bool(int(value))
        elif key == 'scale':
            params['scale'] = value
        elif key == 'greyscale':
            params['greyscale'] = bool(int(value))
        elif key == 'rotation':
            params['rotation'] = value
        elif key == 'quality':
            params['quality'] = int(value)
        elif key == 'obscure':
            params['obscure'] = bool(int(value))
        elif key == 'random_position_once':
            params['random_position_once'] = bool(int(value))

    return Watermarker()(**params)
637262
protected function addWatermarkFilterIfExists(&$set, $width, $height)
    {
        if( isset($set['watermark']) )
        {
            if( ! empty($set['watermark'][1])) 
            {
                $set['filters'][] = ['target', [$set['watermark'][1]]];
            }

            if( ! empty($set['watermark'][2])) 
            {
                $set['filters'][] = ['margin', [$set['watermark'][2]]];
            }

            $set['filters'][] = ['mix', [$set['watermark'][0]]];
        }  
    }
455869
def gen_image(img, width, height, outfile, img_type='grey'):
    """"""
    assert len(img) == width * height or len(img) == width * height * 3

    if img_type == 'grey':
        misc.imsave(outfile, img.reshape(width, height))

    elif img_type == 'color':
        misc.imsave(outfile, img.reshape(3, width, height))
26664
public function watermark($file, $offsetX = 0, $offsetY = 0, $opacity = 1.0)
    {
        $this->do_watermark($file, $offsetX, $offsetY, $opacity);

        return $this;
    }
918065
def show_image(self, key):
        """"""
        data = self.model.get_data()
        data[key].show()
926144
function addImage( &$img, $x, $y, $w = 0, $h = 0, $quality = 75 )
    {
        // add a new image into the current location, as an external object
        // add the image at $x,$y, and with width and height as defined by $w & $h

        // note that this will only work with full colour images and makes them jpg images for display
        // later versions could present lossless image formats if there is interest.

        // there seems to be some problem here in that images that have quality set above 75 do not appear
        // not too sure why this is, but in the meantime I have restricted this to 75.
        if ( $quality > 75 )
        {
            $quality = 75;
        }

        // if the width or height are set to zero, then set the other one based on keeping the image
        // height/width ratio the same, if they are both zero, then give up :)
        $imageWidth = imagesx( $img );
        $imageHeight = imagesy( $img );

        if ( $w <= 0 && $h <= 0 )
        {
            return;
        }
        if ( $w == 0 )
        {
            $w = $h / $imageHeight * $imageWidth;
        }
        if ( $h == 0 )
        {
            $h = $w * $imageHeight / $imageWidth;
        }

        // gotta get the data out of the img..

        // so I write to a temp file, and then read it back.. soo ugly, my apologies.
        $tmpDir = '/tmp';
        $tmpName = tempnam( $tmpDir, 'img' );
        imagejpeg( $img, $tmpName, $quality );

        $fp = fopen( $tmpName, 'rb' );
        if ( $fp )
        {
            $data = '';
            while ( !feof( $fp ) )
            {
                $data .= fread( $fp, 1024 );
            }
            fclose( $fp );
        }
        else
        {
            $error = 1;
            $errormsg = 'trouble opening file';
        }
        unlink( $tmpName );
        $this->addJpegImage_common( $data, $x, $y, $w, $h, $imageWidth, $imageHeight );
    }
557503
function( url, filename )
            {
                var html = '<img id="wysiwyg-insert-image" src="" alt=""' + (filename ? ' title="'+html_encode(filename)+'"' : '') + '>';
                wysiwygeditor.insertHTML( html ).closePopup().collapseSelection();
                var $image = $('#wysiwyg-insert-image').removeAttr('id');
                if( max_imagesize )
                {
                    $image.css({maxWidth: max_imagesize[0]+'px',
                                maxHeight: max_imagesize[1]+'px'})
                          .load( function() {
                                $image.css({maxWidth: '',
                                            maxHeight: ''});
                                // Resize $image to fit "clip-image"
                                var image_width = $image.width(),
                                    image_height = $image.height();
                                if( image_width > max_imagesize[0] || image_height > max_imagesize[1] )
                                {
                                    if( (image_width/image_height) > (max_imagesize[0]/max_imagesize[1]) )
                                    {
                                        image_height = parseInt(image_height / image_width * max_imagesize[0]);
                                        image_width = max_imagesize[0];
                                    }
                                    else
                                    {
                                        image_width = parseInt(image_width / image_height * max_imagesize[1]);
                                        image_height = max_imagesize[1];
                                    }
                                    $image.prop('width',image_width)
                                          .prop('height',image_height);
                                }
                            });
                }
                $image.prop('src', url);
            }
1211474
def make_transparent(image):
    """"""
    data = image.copy().getdata()
    modified = []
    for item in data:
        if _check_pixel(item) is True:
            modified.append((255, 255, 255, 255))  # White transparent pixel
            continue
        modified.append(item)
    image.putdata(modified)
    return image
1312017
private static long adjustWatermark(String baseWatermark, WatermarkType watermarkType) {
    long result = ConfigurationKeys.DEFAULT_WATERMARK_VALUE;
    switch (watermarkType) {
      case SIMPLE:
        result = SimpleWatermark.adjustWatermark(baseWatermark, 0);
        break;
      case DATE:
        result = DateWatermark.adjustWatermark(baseWatermark, 0);
        break;
      case HOUR:
        result = HourWatermark.adjustWatermark(baseWatermark, 0);
        break;
      case TIMESTAMP:
        result = TimestampWatermark.adjustWatermark(baseWatermark, 0);
        break;
    }
    return result;
  }
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);
            }
        }
    }
1239693
public function watermark(AbstractWatermark $watermark)
    {
        $resampleImageResource =& $this->getResampleImageResource();

        if ($watermark instanceof Text) {

            $draw = new \GmagickDraw();
            $draw->setFont($watermark->getFontPath());
            $draw->setFontSize($watermark->getFontSize());
            $draw->setFillColor($watermark->getFontColor());

            if (false !== ($textAxis = $watermark->getAxis())) {
                $draw->annotation($textAxis->getX(), $textAxis->getY(), $watermark->getString());
            } else {
                switch ($watermark->getPosition()) {
                    default:
                    case 'MIDDLE_MIDDLE':
                    case 'MIDDLE':
                    case 'CENTER':
                        $draw->setgravity(\Gmagick::GRAVITY_CENTER);
                        break;

                    case 'MIDDLE_LEFT':
                        $draw->setgravity(\Gmagick::GRAVITY_WEST);
                        break;

                    case 'MIDDLE_RIGHT':
                        $draw->setgravity(\Gmagick::GRAVITY_EAST);
                        break;

                    case 'MIDDLE_TOP':
                        $draw->setgravity(\Gmagick::GRAVITY_NORTH);
                        break;

                    case 'MIDDLE_BOTTOM':
                        $draw->setgravity(\Gmagick::GRAVITY_SOUTH);
                        break;

                    case 'TOP_LEFT':
                        $draw->setgravity(\Gmagick::GRAVITY_NORTHWEST);
                        break;

                    case 'TOP_RIGHT':
                        $draw->setgravity(\Gmagick::GRAVITY_NORTHEAST);
                        break;

                    case 'BOTTOM_LEFT':
                        $draw->setgravity(\Gmagick::GRAVITY_SOUTHWEST);
                        break;

                    case 'BOTTOM_RIGHT':
                        $draw->setgravity(\Gmagick::GRAVITY_SOUTHEAST);
                        break;
                }
            }

            try {

                $resampleImageResource->annotateimage(
                    $draw,
                    $watermark->getPadding(),
                    $watermark->getPadding(),
                    $watermark->getAngle(),
                    $watermark->getString()
                );

                return true;

            } catch (\GmagickException $e) {

                $this->errors[ $e->getCode() ] = $e->getMessage();

            }
        } elseif ($watermark instanceof Overlay) {
            $watermarkImage = new self;
            $watermarkImage->setSourceImage($watermark->getImagePath());
            $watermarkImage->createFromSource();

            $watermarkImageFile = $watermarkImage->getSourceImageFile();
            $watermarkImageDimension = $watermarkImageFile->getDimension();
            $watermarkImageDimension->maintainAspectRatio = true;

            $resampleImageDimension = $this->resampleImageFile->getDimension();

            if (false === ($scale = $watermark->getImageScale())) {
                $scale = min(
                    round((($resampleImageDimension->getWidth() / 2) / $watermarkImageDimension->getWidth()) * 100),
                    round((($resampleImageDimension->getHeight() / 2) / $watermarkImageDimension->getHeight()) * 100)
                );
            }

            if ($scale > 0) {
                $watermarkImage->setResampleImage($watermarkImageFile->withDimension(
                    $watermarkImageDimension
                        ->withScale($scale)
                ));
            }

            $watermarkImageDimension = $watermarkImage->getResampleImageFile()->getDimension();

            if ($watermarkImage->scale()) {
                $watermarkImageResource = $watermarkImage->getResampleImageResource();

                if (false !== ($watermarkAxis = $watermark->getAxis())) {
                    $watermarkImageAxisX = $watermarkAxis->getX();
                    $watermarkImageAxisY = $watermarkAxis->getY();
                } else {
                    switch ($watermark->getPosition()) {
                        default:
                        case 'MIDDLE_MIDDLE':
                        case 'MIDDLE':
                        case 'CENTER':
                            $watermarkImageAxisX = ($resampleImageDimension->getWidth() - $watermarkImageDimension->getWidth()) / 2;
                            $watermarkImageAxisY = ($resampleImageDimension->getHeight() - $watermarkImageDimension->getHeight()) / 2;
                            break;

                        case 'MIDDLE_LEFT':
                            $watermarkImageAxisX = $watermark->getPadding();
                            $watermarkImageAxisY = ($resampleImageDimension->getHeight() - $watermarkImageDimension->getHeight()) / 2;
                            break;

                        case 'MIDDLE_RIGHT':
                            $watermarkImageAxisX = $resampleImageDimension->getWidth() - ($watermarkImageDimension->getWidth() + $watermark->getPadding());
                            $watermarkImageAxisY = ($resampleImageDimension->getHeight() - $watermarkImageDimension->getHeight()) / 2;
                            break;

                        case 'MIDDLE_TOP':
                            $watermarkImageAxisX = ($resampleImageDimension->getWidth() - $watermarkImageDimension->getWidth()) / 2;
                            $watermarkImageAxisY = $watermarkImageDimension->getHeight() + $watermark->getPadding();
                            break;

                        case 'MIDDLE_BOTTOM':
                            $watermarkImageAxisX = ($resampleImageDimension->getWidth() - $watermarkImageDimension->getWidth()) / 2;
                            $watermarkImageAxisY = $resampleImageDimension->getHeight() - ($watermarkImageDimension->getHeight() + $watermark->getPadding());
                            break;

                        case 'TOP_LEFT':
                            $watermarkImageAxisX = $watermark->getPadding();
                            $watermarkImageAxisY = $watermarkImageDimension->getHeight() + $watermark->getPadding();
                            break;

                        case 'TOP_RIGHT':
                            $watermarkImageAxisX = $resampleImageDimension->getWidth() - ($watermarkImageDimension->getWidth() + $watermark->getPadding());
                            $watermarkImageAxisY = $watermarkImageDimension->getHeight() + $watermark->getPadding();
                            break;

                        case 'BOTTOM_LEFT':
                            $watermarkImageAxisX = $watermark->getPadding();
                            $watermarkImageAxisY = $resampleImageDimension->getHeight() - $watermarkImageDimension->getHeight() + $watermark->getPadding();
                            break;

                        case 'BOTTOM_RIGHT':
                            $watermarkImageAxisX = $resampleImageDimension->getWidth() - ($watermarkImageDimension->getWidth() + $watermark->getPadding());
                            $watermarkImageAxisY = $resampleImageDimension->getHeight() - ($watermarkImageDimension->getHeight() + $watermark->getPadding());
                            break;
                    }
                }

                try {
                    $resampleImageResource->compositeimage($watermarkImageResource, \Gmagick::COMPOSITE_OVER,
                        $watermarkImageAxisX,
                        $watermarkImageAxisY);

                    return true;
                } catch (\GmagickException $e) {
                    $this->errors[ $e->getCode() ] = $e->getMessage();
                }
            }
        }

        return false;
    }
1292031
def render_image(**kwargs):
    
    html = ''

    url = kwargs.get('url', None)
    if url:
        html = '<img'

        alt_text = kwargs.get('alt_text', None)
        if alt_text:
            html += ' alt="{}"'.format(alt_text)

        title = kwargs.get('title', None)
        if title:
            html += ' title="{}"'.format(title)

        html += ' src="{}">'.format(url)

    return html
1315830
def add_pic(self, post_data):
        '''
        
        '''
        img_entity = self.request.files['file'][0]
        filename = img_entity["filename"]

        if filename and allowed_file(filename):
            pass
        else:
            return False

        _, hou = os.path.splitext(filename)
        signature = str(uuid.uuid1())
        outfilename = '{0}{1}'.format(signature, hou)
        outpath = 'static/upload/{0}'.format(signature[:2])
        if os.path.exists(outpath):
            pass
        else:
            os.makedirs(outpath)
        with open(os.path.join(outpath, outfilename), "wb") as fileout:
            fileout.write(img_entity["body"])
        path_save = os.path.join(signature[:2], outfilename)
        sig_save = os.path.join(signature[:2], signature)

        imgpath = os.path.join(outpath, signature + '_m.jpg')
        imgpath_sm = os.path.join(outpath, signature + '_sm.jpg')

        ptr_image = Image.open(os.path.join('static/upload', path_save))
        tmpl_size = (768, 768)
        thub_size = (256, 256)
        (imgwidth, imgheight) = ptr_image.size
        if imgwidth < tmpl_size[0] and imgheight < tmpl_size[1]:
            tmpl_size = (imgwidth, imgheight)
        ptr_image.thumbnail(tmpl_size)

        im0 = ptr_image.convert('RGB')
        im0.save(imgpath, 'JPEG')

        im0.thumbnail(thub_size)
        im0.save(imgpath_sm, 'JPEG')

        create_pic = MEntity.create_entity(signature,
                                           path_save,
                                           post_data['desc'] if 'desc' in post_data else '',
                                           kind=post_data['kind'] if 'kind' in post_data else '1')
        if self.entity_ajax == False:
            self.redirect('/entity/{0}_m.jpg'.format(sig_save))
        else:
            if create_pic:
                output = {'path_save': imgpath}
            else:
                output = {'path_save': ''}
            return json.dump(output, self)
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());
	}
252056
def save_image(self, img, filename=None, **kwargs):  # floating_point=False,
        
        filename = filename or self.get_filename(**img.data.attrs)
        nt.save(img, filename, **kwargs)
760286
def add(self, document, watermark):
        """"""
        # 5a. Create output PDF file name
        output_filename = self.output_filename

        def pypdf3():
            """Much slower than PyPDF3 method."""
            # 5b. Get our files ready
            document_reader = PdfFileReader(document)
            output_file = PdfFileWriter()

            # Number of pages in input document
            page_count = document_reader.getNumPages()

            # Watermark objects
            watermark_reader = PdfFileReader(watermark)
            wtrmrk_page = watermark_reader.getPage(0)
            wtrmrk_width = (wtrmrk_page.mediaBox.getWidth() / 2) + 0
            wtrmrk_height = (wtrmrk_page.mediaBox.getHeight() / 2) + 80
            wtrmrk_rotate = -int(Info(watermark_reader).rotate) if Info(watermark_reader).rotate is not None else 0

            # 5c. Go through all the input file pages to add a watermark to them
            for page_number in range(page_count):
                # Merge the watermark with the page
                if not self.underneath:
                    input_page = document_reader.getPage(page_number)
                    if wtrmrk_rotate is not 0:
                        input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height)
                    else:
                        wtrmrk_width = 0
                        wtrmrk_height = 0
                        input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height)
                else:
                    size = Info(document_reader).dimensions
                    input_page = PageObject().createBlankPage(document_reader, size['w'], size['h'])
                    if wtrmrk_rotate is not 0:
                        input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height)
                    else:
                        wtrmrk_width = 0
                        wtrmrk_height = 0
                        input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height)
                    input_page.mergePage(document_reader.getPage(page_number))

                # Add page from input file to output document
                output_file.addPage(input_page)

            # 5d. finally, write "output" to PDF
            with open(output_filename, "wb") as outputStream:
                output_file.write(outputStream)
            return output_filename

        def pdfrw():
            """Faster than PyPDF3 method by as much as 15x."""
            # TODO: Fix issue where watermark is improperly placed on large pagesize PDFs
            # print(Info(document).size)
            # print(Info(watermark).size)
            # print('\n')

            # Open both the source files
            wmark_trailer = PdfReader(watermark)
            trailer = PdfReader(document)

            # Handle different sized pages in same document with
            # a memoization cache, so we don't create more watermark
            # objects than we need to (typically only one per document).

            wmark_page = wmark_trailer.pages[0]
            wmark_cache = {}

            # Process every page
            for pagenum, page in enumerate(trailer.pages, 1):

                # Get the media box of the page, and see
                # if we have a matching watermark in the cache
                mbox = tuple(float(x) for x in page.MediaBox)
                odd = pagenum & 1
                key = mbox, odd
                wmark = wmark_cache.get(key)
                if wmark is None:

                    # Create and cache a new watermark object.
                    wmark = wmark_cache[key] = PageMerge().add(wmark_page)[0]

                    # The math is more complete than it probably needs to be,
                    # because the origin of all pages is almost always (0, 0).
                    # Nonetheless, we illustrate all the values and their names.

                    page_x, page_y, page_x1, page_y1 = mbox
                    page_w = page_x1 - page_x
                    page_h = page_y1 - page_y  # For illustration, not used

                    # Scale the watermark if it is too wide for the page
                    # (Could do the same for height instead if needed)
                    if wmark.w > page_w:
                        wmark.scale(1.0 * page_w / wmark.w)

                    # Always put watermark at the top of the page
                    # (but see horizontal positioning for other ideas)
                    wmark.y += page_y1 - wmark.h

                    # For odd pages, put it at the left of the page,
                    # and for even pages, put it on the right of the page.
                    if odd:
                        wmark.x = page_x
                    else:
                        wmark.x += page_x1 - wmark.w

                    # Optimize the case where the watermark is same width
                    # as page.
                    if page_w == wmark.w:
                        wmark_cache[mbox, not odd] = wmark

                # Add the watermark to the page
                PageMerge(page).add(wmark, prepend=self.underneath).render()

            # Write out the destination file
            PdfWriter(output_filename, trailer=trailer).write()

        if self.method is 'pypdf3':
            return pypdf3()
        else:
            return pdfrw()