2016-05-17 114 views
0

在Linux控制檯中,如果使用identify -verbose file.png,它會爲您提供文件的完整打印。反正有沒有在PHP中獲得相同的信息?使用PHP獲取png類型

具體而言,我需要指出png類型的「Type」行。 TrueColorAlpha,PaletteAlpha等。

爲什麼? 操作系統損壞,並試圖重建一個超過500萬圖像的結構,其中200萬的圖像被丟失並找到。其中一些是系統創建的,其中一些已經上傳。如果我能夠找到兩者之間的差異,這將節省大量的時間。

+3

您可以執行'$ output = shell_exec(「identify -verbose $ filename」)'並獲得與從終端運行'identify'相同的結果。 – apokryfos

+0

你是絕對正確的。我確實知道高管,但我想知道是否有另一種方式,基於我已經不得不做的事情。如果不是這樣很好,那就是我要去的地方。 – Iscariot

+0

嗯,我認爲你必須經歷更多的麻煩,純粹使用PHP,然後執行一些bash代碼。 –

回答

-1

使用bash代碼做在你的PHP Executing a Bash script from a PHP script

<?php 
     $type=shell_exec("identify -verbose $filename"); 
     print_r($type); 
?> 
+0

問題在於我需要對此變量進行編程訪問。只要能夠在PHP中讀取它對我沒有幫助。 – Iscariot

+0

「在linux控制檯中,如果使用了identify -verbose file.png,它會給你一個完整的文件打印出來,有沒有辦法在php中獲取相同的信息?」這是你的問題的答案...也許你應該編輯你的問題,然後如果它是你想要的東西。 –

+0

您在發佈答案之前閱讀了評論。你知道我想要什麼。 – Iscariot

1

從這些文章中,我寫了一個簡單的功能不是可以給你一個PNG文件的顏色類型:

https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header

http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html

簡而言之:PNG文件由標題和塊組成。在第二個標頭中,第四個字節應該是等於「PNG」的ASCII字符串,然後是名稱爲4字節的塊。 IHDR塊向您提供有關像,高度和所需顏色類型的圖像數據。該塊的位置始終是固定的,因爲它始終是第一塊。它的內容在我給你的第二個鏈接中描述:

IHDR塊必須顯示爲第一個。它包含:

Width:    4 bytes 
    Height:    4 bytes 
    Bit depth:   1 byte 
    Color type:   1 byte 
    Compression method: 1 byte 
    Filter method:  1 byte 
    Interlace method: 1 byte 

因此,瞭解標題的塊名稱的長度,長度和它的結構,我們可以計算出顏色類型數據的位置和它的26個字節。現在我們可以編寫一個簡單的函數來讀取PNG文件的顏色類型。

function getPNGColorType($filename) 
{ 
    $handle = fopen($filename, "r"); 

    if (false === $handle) { 
     echo "Can't open file $filename for reading"; 
     exit(1); 
    } 

    //set poitner to where the PNG chunk shuold be 
    fseek($handle, 1); 
    $mime = fread($handle, 3); 
    if ("PNG" !== $mime) { 
     echo "$filename is not a PNG file."; 
     exit(1); 
    } 

    //set poitner to the color type byte and read it 
    fseek($handle, 25); 
    $content = fread($handle, 1); 
    fclose($handle); 

    //get integer value 
    $unpack = unpack("c", $content); 

    return $unpack[1]; 
} 

$filename = "tmp/png.png"; 
getPNGColorType($filename); 

這裏是顏色類型命名(從第二個鏈接):

Color Allowed  Interpretation 
    Type Bit Depths 

    0  1,2,4,8,16 Each pixel is a grayscale sample. 

    2  8,16  Each pixel is an R,G,B triple. 

    3  1,2,4,8  Each pixel is a palette index; 
         a PLTE chunk must appear. 

    4  8,16  Each pixel is a grayscale sample, 
         followed by an alpha sample. 

    6  8,16  Each pixel is an R,G,B triple, 

我希望這有助於。

+1

爲什麼要投票? –