duandun3178 2016-10-08 20:01
浏览 62
已采纳

想象一下,如果open()方法抛出异常忽略然后继续下一个循环

I am trying to use Imagine to batch make 250x250 thumbnail of more than 90k+ relatively small mobile images. The problem is, when I run a loop,

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

sometimes, the image is corrupted and the open() method fails, throwing exception:

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

and completely breaks the loop. Is there a way, to check if open failed? something like:

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 />';
  }
}

Hope somebody can help. or if its not possible, can you suggest a PHP image library that I can pragmatically resize by batch?

Thank you

  • 写回答

1条回答 默认 最新

  • dsizmmwnm56437180 2016-10-08 20:08
    关注

    For handling the exception just use try-catch.

    From the library documentation

    The ImagineInterface::open() method may throw one of the following exceptions:

    Imagine\Exception\InvalidArgumentException

    Imagine\Exception\RuntimeException

    Try it like this:

    $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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?