【问题标题】:Imagine if open() method threw exception ignore then proceed to the next loop想象一下如果 open() 方法抛出异常忽略然后继续下一个循环
【发布时间】:2017-02-17 14:35:29
【问题描述】:

我正在尝试使用Imagine 批量制作超过 90k+ 相对较小的移动图像的 250x250 缩略图。问题是,当我运行一个循环时,

foreach ($images as $c) {
  $imagine = new Imagine();
  $image = $imagine->open($c);
  $image->resize(new Box(250, 250))->save($outFolder);
}

有时,图像已损坏,open() 方法失败,抛出异常:

Unable to open image vendor/imagine/imagine/lib/Imagine/Gd/Imagine.php Line: 96

并完全打破循环。有没有办法检查open 是否失败?类似:

foreach ($images as $c) {
  $imagine = new Imagine();
  $image = $imagine->open($c);
  if ($image) {
     $image->resize(new Box(250, 250))->save($outFolder);
  } else {
     echo 'corrupted: <br />';
  }
}

希望有人可以提供帮助。或者如果不可能,你能推荐一个我可以批量调整大小的 PHP 图像库吗?

谢谢

【问题讨论】:

    标签: php batch-file image-processing php-imagine


    【解决方案1】:

    要处理异常,只需使用try-catch

    来自图书馆documentation

    ImagineInterface::open() 方法可能会抛出以下异常之一:

    想象\Exception\InvalidArgumentException

    想象\异常\运行时异常

    试试这样:

    $imagine = new Imagine(); // Probably no need to instantiate it in every loop
    foreach ($images as $c) {
        try {
            $image = $imagine->open($c);
        } catch (\Exception $e) {
            echo 'corrupted: <br />';
            continue;
        }
        $image->resize(new Box(250, 250))->save($outFolder);
    }
    

    【讨论】:

    • 谢谢!这实际上是我在现实生活中第一次使用异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2019-10-22
    • 2021-05-13
    • 1970-01-01
    • 2012-09-15
    • 2018-03-20
    相关资源
    最近更新 更多