繁体   English   中英

imagecreatefromstring-捕获失败-PHP

[英]imagecreatefromstring - catch fail - PHP

我试图在给定URL时检测图像是否为图像。 要从网址保存图片,我使用了以下内容:

// create the image and save it
$imagefile = $URL;
$resource = imagecreatefromstring(file_get_contents($imagefile));
// X amount of quality is the last number
imagejpeg($resource, "images/covers/$imagepath.jpeg", 50);
imagedestroy($resource);

$ URL只是用户提供的图像链接。

我尝试了以下方法:

$imagefile = $addBuildCover;
$resource = imagecreatefromstring(file_get_contents($imagefile));

if ($resource !== false) {
  $return['imageGood'] = true;  
} else {
  $return['imageBad'] = true;
}

我已经尝试过该代码,并且返回了'imageBad'的正确JSON返回值,但是它给了我一个错误,之前是:

Warning: file_get_contents(ewffw.png): failed to open stream: No such file or directory in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116

Warning: imagecreatefromstring(): Empty string or invalid image in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 116

如何尝试捕获URL失败但实际上没有像上面那样返回错误?

不幸的是,如果您将无效的数据传递给了imagecreatefromstring ,则使用它会产生不必要的问题。

您将不得不使用错误抑制运算符@将其关闭:

$resource = @imagecreatefromstring(file_get_contents($imagefile));

通常不赞成使用此运算符,但是这种情况确实是有合法用例的。

如果无法加载文件,此方法还将处理file_get_contents发出的警告。 该函数的表现并不那么差(有多种方法可以合理确定是否会失败,例如is_readable ),因此您可以使用代码而不是使用@检查,但是由于您仍然需要抑制错误,因此没有区别如果文件读取失败与否,恕我直言,恕我直言此处完全拍了拍@

<?php
    $serverName = "server";

    $uid = "user";
    $pwd = "pass";
    $connectionInfo = array( "UID"=>$uid,
                             "PWD"=>$pwd,
                             "Database"=>"database");


    $conn = sqlsrv_connect( $serverName, $connectionInfo);
    if( $conn === false )
    {
         echo "Unable to connect.</br>";
         die( print_r( sqlsrv_errors(), true));
    }


    $fotoquery = "SELECT column_image FROM Table WHERE Column = 'xxxxxxxxxx'";

    $stmt = sqlsrv_query( $conn, $fotoquery);

    if( $stmt === false )
    {
       echo "Error in executing query.</br>";
       die( print_r( sqlsrv_errors(), true));
    }

    $dataImage = sqlsrv_fetch_array($stmt);
    $varimg = base64_encode($dataImage[0]);

    $data = base64_decode($varimg);

    $im = imagecreatefromstring($data);
    if ($im !== false) {
        header('Content-Type: image/png');
        imagepng($im);
        imagedestroy($im);
    }
    else {
        echo 'An error occurred.';
    }
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM