php使用元数据,如何从PHP读取PNG元数据?

PNG file format定义了一个PNG文档被分割成多个数据块.因此,您必须浏览您想要的大块.

您要提取的数据似乎在text块中定义.我写了下面的类来允许你从PNG文件中提取块.

class PNG_Reader

{

private $_chunks;

private $_fp;

function __construct($file) {

if (!file_exists($file)) {

throw new Exception('File does not exist');

}

$this->_chunks = array ();

// Open the file

$this->_fp = fopen($file, 'r');

if (!$this->_fp)

throw new Exception('Unable to open file');

// Read the magic bytes and verify

$header = fread($this->_fp, 8);

if ($header != "\x89PNG\x0d\x0a\x1a\x0a")

throw new Exception('Is not a valid PNG image');

// Loop through the chunks. Byte 0-3 is length, Byte 4-7 is type

$chunkHeader = fread($this->_fp, 8);

while ($chunkHeader) {

// Extract length and type from binary data

$chunk = @unpack('Nsize/a4type', $chunkHeader);

// Store position into internal array

if ($this->_chunks[$chunk['type']] === null)

$this->_chunks[$chunk['type']] = array ();

$this->_chunks[$chunk['type']][] = array (

'offset' => ftell($this->_fp),

'size' => $chunk['size']

);

// Skip to next chunk (over body and CRC)

fseek($this->_fp, $chunk['size'] + 4, SEEK_CUR);

// Read next chunk header

$chunkHeader = fread($this->_fp, 8);

}

}

function __destruct() { fclose($this->_fp); }

// Returns all chunks of said type

public function get_chunks($type) {

if ($this->_chunks[$type] === null)

return null;

$chunks = array ();

foreach ($this->_chunks[$type] as $chunk) {

if ($chunk['size'] > 0) {

fseek($this->_fp, $chunk['offset'], SEEK_SET);

$chunks[] = fread($this->_fp, $chunk['size']);

} else {

$chunks[] = '';

}

}

return $chunks;

}

}

您可以使用它来提取您想要的tEXt块:

$file = '18201010338AM16390621000846.png';

$png = new PNG_Reader($file);

$rawTextData = $png->get_chunks('tEXt');

$metadata = array();

foreach($rawTextData as $data) {

$sections = explode("\0", $data);

if($sections > 1) {

$key = array_shift($sections);

$metadata[$key] = implode("\0", $sections);

} else {

$metadata[] = $data;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值