输出有点像我想要的,但我真的只需要第 3-7 行(含)。这就是现在的输出:http://silentnoobs.com/pbss/collector/t-6ren">
gpt4 book ai didi

php - 如何从 PHP 读取 PNG 元数据?

转载 作者:可可西里 更新时间:2023-10-31 22:10:05 25 4
gpt4 key购买 nike

这是我目前所拥有的:

<?php

$file = "18201010338AM16390621000846.png";

$test = file_get_contents($file, FILE_BINARY);

echo str_replace("\n","<br>",$test);

?>

输出有点像我想要的,但我真的只需要第 3-7 行(含)。这就是现在的输出:http://silentnoobs.com/pbss/collector/test.php .我正在尝试将数据从“PunkBuster Screenshot (±) AAO Bridge Crossing”获取到“Resulting: w=394 X h=196 sample=2”。我认为通读文件并将每一行存储在一个数组中是相当直接的,行 [0] 需要是“PunkBuster Screenshot (±) AAO Bridge Crossing”,等等。所有这些行都可能发生变化,所以我不能只搜索有限的东西。

我已经尝试了几天了,但我的 php 水平很差,这并没有多大帮助。

最佳答案

PNG file format定义将 PNG 文档拆分为多个数据 block 。因此,您必须导航到您想要的 block 。

您要提取的数据似乎是在 tEXt block 中定义的。我编写了以下类以允许您从 PNG 文件中提取 block 。

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 block :

$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;
}
}

关于php - 如何从 PHP 读取 PNG 元数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2190236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com