[英]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.