0

我正在为用 php 编写的图像下载服务编写测试用例。我们正在使用 phpunit。如何检查检索到的二进制数据是否为图像?

4

1 回答 1

2

使用exif_imagetype(见手册)很好,但确实需要你必须在本地磁盘上的文件。如果您不介意硬编码一些幻数,您可以直接检查图像类型,请参见testFetchWithoutSaving下一个示例:

class ImageTest extends PHPUnit_Framework_TestCase
{

/**
* @see http://stackoverflow.com/a/676975/841830
*/
public function testFetchWithoutSaving(){
    $s=file_get_contents("https://www.google.com/images/srpr/logo3w.png");
    $this->assertEquals("\x89PNG\x0d\x0a\x1a\x0a",substr($s,0,8));

    $s=file_get_contents("https://www.google.com/");
    $this->assertEquals("\x89PNG\x0d\x0a\x1a\x0a",substr($s,0,8),"Fails: first 8 bytes are actually '<!doctyp'");
    }

/**
* @see http://php.net/manual/en/function.exif-imagetype.php
*/
public function testFetchWithTempFile(){
    $s=file_get_contents("https://www.google.com/images/srpr/logo3w.png");
    $tempFilename="/tmp/phpunit.testImage.testFetchWithTempFile";
    file_put_contents($tempFilename,$s);
    $type=exif_imagetype($tempFilename);
    unlink($tempFilename);
    $this->assertTrue($type!==false);   //Any recognized image type
    $this->assertEquals(IMAGETYPE_PNG,$type);   //A specific image type
    }

}
于 2012-08-16T00:20:55.747 回答