2012-08-15 84 views
0

我正在寫圖像下載服務寫在PHP測試用例。我們使用phpunit。如何檢查檢索到的二進制數據是否爲圖像?Phpunit圖像下載測試

+0

,以確定是否一個URL是在圖像[最好的方式重複PHP的](http://stackoverflow.com/questions/676949/best-way-to-determine-if-a-url-is-an-image-in-php)和http://stackoverflow.com/questions/ 10662915 /檢查文件是否是圖像或不是和http://stackoverflow.com/questions/6391916/is-it-important-to-verify-that-the-uploaded-file- is-an-an-image-file – 2012-08-15 12:25:51

+0

'getimagesize()'是某些圖像格式的家喻戶曉的名稱。你需要支持哪些? – 2012-08-15 12:26:11

回答

1

使用exif_imagetype(請參閱manual)很好,但確實需要您必須將文件放在本地磁盤上。如果你不介意硬編碼一些神奇的數字,你可以檢查圖像類型直接看到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 
    } 

}