php 无法处理imagecreatefromstring中的假或异常

6jjcrrmo  于 2022-12-25  发布在  PHP
关注(0)|答案(1)|浏览(156)

如何处理php函数imagecreatefromstring的异常或返回'false'。在下面的代码中,我试图触发false只是中断,例如当我试图加载zip时,不要返回false。

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//zip file
 $stringImage = $file->getStream()->getContents();
    if (false === imagecreatefromstring($stringImage)){
        echo CJSON::encode(new JSONError('Error'));
}

研究结果:
图像创建自字符串():数据的格式无法识别

xa9qqrwz

xa9qqrwz1#

全规格https://www.php.net/manual/en/errorfunc.constants.php
我留下了一个示例代码。我希望它会方便你。

$zip = new ZipArchive;
$zHandle = $zip->open(dirname(__FILE__) . DIRECTORY_SEPARATOR . "contains.png.zip");
// $zHandle = $zip->open(dirname(__FILE__) . DIRECTORY_SEPARATOR . "contains.txt.zip");
if($zHandle && $zip->numFiles == 1){
    $im_string = $zip->getFromName($zip->statIndex(0)['name']);
    $zip->close();
    $im = imagecreatefromstring($im_string);

    // That's what you care about...
    $err = error_get_last();
    if ($err['type'] ==  2) {
        echo "\nWe have a warning ...";
        echo "\nMessage:".$err['message'];
        echo "\nFile:".$err['file'];
        echo "\nLine:".$err['line'];
        return;
    }

    header('Content-Type: image/png');
    imagepng($im);
} else {
    throw new \Exception("Ups ... check your handle or check the real number of zipped files.", 1);
}

相关问题