[英]Using PHP get png type
在Linux控制台中,如果使用identify -verbose file.png
它將為您提供文件的完整打印。 反正有沒有得到相同的信息在PHP?
具體來說,我需要“類型”行來說明png的類型。 TrueColorAlpha,PaletteAlpha等
為什么? 操作系統損壞,並試圖重建超過500萬張圖像的結構,其中200萬張圖像被丟棄並丟失。 其中一些是系統創建的,其中一些已上傳。 如果我能夠找到兩者之間的區別,那將節省大量時間。
從這些文章中,我編寫了一個簡單的函數,可以為您提供PNG文件的顏色類型:
https://zh.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,
我希望這有幫助。
使用PHP中的Bash代碼執行此操作從PHP腳本執行Bash腳本
<?php
$type=shell_exec("identify -verbose $filename");
print_r($type);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.