Last active
July 29, 2023 17:34
-
-
Save kamermans/0c5759fdaaa9fb3eeaaccf1e9a962b9d to your computer and use it in GitHub Desktop.
ImageMagick identify -verbose JSON transformer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php namespace kamermans\ImageMagick; | |
/** | |
* Parser for the ImageMagick "identify" utility that takes "identify -verbose <file>" | |
* output on STDIN and outputs JSON on STDOUT. | |
* | |
* Example: | |
* identify -verbose foo.jpg | ./parse_identify.php | |
*/ | |
class IdentifyParser { | |
private $data = []; | |
private $line_number = 0; | |
public function parse($content) | |
{ | |
if (is_array($content)) { | |
$lines = $content; | |
} else if (is_resource($content)) { | |
$lines = explode("\n", stream_get_contents($content)); | |
} else { | |
$lines = explode("\n", $content); | |
} | |
$raw_data = $this->doParse($lines); | |
$this->data = $raw_data['Image']; | |
$this->line_number = 0; | |
} | |
public function toJson($flags=null) | |
{ | |
return json_encode($this->data, $flags); | |
} | |
public function __toString() | |
{ | |
return $this->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); | |
} | |
public function toArray() | |
{ | |
return $this->data; | |
} | |
public function __get($key) | |
{ | |
return array_key_exists($key, $this->data)? $this->data[$key]: false; | |
} | |
private function doParse($lines, $my_depth=0) | |
{ | |
$data = []; | |
while(true) { | |
if ($this->line_number >= count($lines)) { | |
break; | |
} | |
$line = rtrim($lines[$this->line_number++]); | |
if (strlen($line) === 0) { | |
continue; | |
} | |
if (!preg_match('/^( *)\b(.+?): *(.*)$/', $line, $matches)) { | |
die("Unable to parse line:\n'$line'\n"); | |
} | |
list($match, $indent, $key, $value) = $matches; | |
$key = trim($key); | |
$value = trim($value); | |
$current_depth = strlen($indent) / 2; | |
if ($current_depth > 0 && $current_depth <= $my_depth) { | |
$this->line_number--; | |
return $data; | |
} | |
if (strlen($value) === 0 || $key == "Image") { | |
$subdata = $this->doParse($lines, $current_depth); | |
$data[$key] = $subdata; | |
if ($key == "Image") { | |
$data[$key] = ['Image' => $value] + $data[$key]; | |
} | |
} else { | |
$data[$key] = $value; | |
} | |
} | |
return $data; | |
} | |
} | |
$parser = new IdentifyParser(); | |
$parser->parse(STDIN); | |
echo "$parser\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment