2016-05-17 119 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

为什么要投票? –