首页 > 解决方案 > 源图像的水印种植者时忽略“OutOfBoundsException”错误

问题描述

Yii2和核心yii\imagine\Image类中,使用此命令时:

Image::watermark('image.jpg', 'watermark.jpg')->save('image.jpg');

如果水印的尺寸,源图像的种植者,返回此错误:

Exception 'Imagine\Exception\OutOfBoundsException' with message 'Cannot paste image of the given size at the specified position, as it moves outside of the current image's box' 

没关系。但是怎么能忽略这个错误,所以会创建新的图像,但图像框之外的水印部分被隐藏和删除。

标签: imageyii2watermark

解决方案


不可忽视这Exceptions就是为什么它们被该名称调用的原因,从paste(ImageInterface $image, PointInterface $start);方法中抛出异常

$size = $image->getSize();
if (!$this->getSize()->contains($size, $start)) {
    throw new OutOfBoundsException('Cannot paste image of the given size at the specified position, as it moves outside of the current image\'s box');
}

Image::watermark函数中调用。它受到限制且不允许,因此您不能忽略它。

您可以忽略/禁止通知或警告,但您可以catch处理异常并做一些事情来修复它或向用户显示错误

try{
    \yii\imagine\Image::watermark ( 'img/image.png' , 'img/logo.jpg' );
} catch (\Imagine\Exception\OutOfBoundsException $ex) {
    Yii::$app->session->setFlash('error',$ex->getMessage()) ;
}

或者如果发生异常,将水印图像调整为小于基本图像的大小并Image::watermark再次调用。

EDIT

你可以像我所说的那样做一些事情,假设你有一个actionWatermark()你正在创建水印图像的地方

public function actionWatermark() {
    $image='image.jpg';
    $watermark= 'watermark.jpg';

    try {
        //call watermark function
        $this->watermark ($image,$watermark);
    } catch ( \Imagine\Exception\OutOfBoundsException $ex ) {
        
        $img = \yii\imagine\Image::getImagine ();
        //get the base image dimensions
        $size=$img->open ( $image )->getSize();
        //resize the watermark image
        $resized=\yii\imagine\Image::resize ( $watermark , $size->getWidth () , $size->getHeight (),TRUE);
        
        //call again
        $this->watermark ($image,$resized);
    }
    
}

private function watermark($image,$watermark) {
    \yii\imagine\Image::watermark ( $image , $watermark )->save ( 'image.jpg' );
}

推荐阅读