如何确保JPEG图像有效并且可以由PHP处理?

时间:2012-09-18 12:28:01

标签: php apache imagemagick gd laravel

我有这个JPEG一直给我正在使用的Resizer library函数imagesx($this->image)带来问题。我可以使用浏览器查看图像,在尝试调整大小时,我收到错误:

imagesx() expects parameter 1 to be resource, boolean given

如果要抛出错误,我可以不处理此文件。我如何使用PHP来检查PHP的图像函数是否可以正确处理这个图像?


调用库的代码

// Download the photo
$img_content = file_get_contents($url);
if($img_content !== FALSE) {
    file_put_contents($img_documentroot . $img_subpath . $img_filename . '_tmp.jpg',
     $img_content);
}

echo $url . '<br>';
echo $img_documentroot . $img_subpath . $img_filename . '_tmp.jpg<br>';
ob_flush();
flush();

// Resize photo
Resizer::open( $img_documentroot . $img_subpath . $img_filename . '_tmp.jpg' )
->resize(300, 300, 'landscape' )
->save($img_documentroot . $img_subpath . $img_filename . '.jpg' , 90 );

// Thumbnail photo
Resizer::open( $img_documentroot . $img_subpath . $img_filename . '_tmp.jpg' )
->resize(100, 100, 'crop' )
->save($img_documentroot . $img_subpath . $img_filename . '.jpg' , 90 );

输出

我也回应了调整大小的图像的完整路径。

http://www.ApartmentsInAllstonMA.com/Images/Apts/132847_kn1.jpg
/home/photos/public_html/2012/0917/2516539_7_tmp.jpg
resource(127) of type (gd)
resource(130) of type (gd)
http://www.ApartmentsInMedford.com/Images/Apts/132847_lv2.jpg
/home/photos/public_html/2012/0917/2516539_11_tmp.jpg
resource(163) of type (gd)
resource(166) of type (gd)
http://www.AllstonApartmentX.com/images/agents/61.jpg
/home/photos/public_html/2012/0917/2516539_12_tmp.jpg
bool(false)

更新

这是导致库返回false值的代码段。

private function open_image( $file )
{

    // If $file isn't an array, we'll turn it into one
    if ( !is_array($file) ) {
        $file = array(
            'type'      => File::mime( strtolower(File::extension($file)) ),
            'tmp_name'  => $file
        );
    }

    $mime = $file['type'];
    $file_path = $file['tmp_name'];

    switch ( $mime )
    {
        case 'image/pjpeg': // IE6
        case File::mime('jpg'): $img = @imagecreatefromjpeg( $file_path );  break;
        case File::mime('gif'): $img = @imagecreatefromgif( $file_path );   break;
        case File::mime('png'): $img = @imagecreatefrompng( $file_path );   break;
        default:                $img = false;                               break;
    }

    return $img;
}

2 个答案:

答案 0 :(得分:3)

检查mime类型是确保JPEG图像有效性的一种非常好的方法。以下是如何做到这一点。

$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type
$type = finfo_file($finfo, $filename) . "\n";  
if($type == "image/jpeg") { 
     //Valid JPEG Image
}
finfo_close($finfo);

根据您的错误,您正在发送布尔值而不是图片资源

答案 1 :(得分:2)

该文件可能具有.JPG扩展名,但这并不一定意味着它是正确的文件类型。我之前看到用户使用.PNG文件并将其重命名为.JPG,认为他们可以通过这种方式在格式之间进行转换。

它也可能是使用CMYK颜色空间而不是RGB颜色空间的有效JPEG文件。每隔一段时间我就会看到其中一个 - 通常来自印刷设计师。我通常在Photoshop中打开它们并查看Image - &gt;模式,看它是RGB还是CMYK。在Windows中,您还可以通过右键单击,选择“属性”,然后在“高级”选项卡下查找来确定颜色空间。