49 lines
1.8 KiB
PHP
49 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace swf2ass;
|
|
|
|
class JPEGBitmapDefinition extends BitmapDefinition {
|
|
|
|
static function fromXML(\DOMElement $element): BitmapDefinition {
|
|
//Utils::dump_element($element);
|
|
|
|
$im = new \Imagick();
|
|
$data = base64_decode(trim($element->textContent));
|
|
$bytes = $element->hasAttribute("offset_to_alpha") ? substr($data, 0, $element->getAttribute("offset_to_alpha")) : $data;
|
|
|
|
$isJPEG = substr($bytes, 0, 2) === "\xff\xd8" || substr($bytes, 0, 4) === "\xff\xd9\xff\xd8";
|
|
|
|
if ($isJPEG) { //Fix freaking broken JPEGs
|
|
if (substr($bytes, 0, 4) === "\xff\xd9\xff\xd8") { //Invalid header before marker
|
|
$bytes = substr($bytes, 4);
|
|
}
|
|
|
|
$size = strlen($bytes);
|
|
for ($i = 0; $i < $size; $i += 4) {
|
|
if (substr($bytes, $i, 4) === "\xff\xd9\xff\xd8") {
|
|
$bytes = substr($bytes, 0, $i) . substr($bytes, $i + 4);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
$im->readImageBlob($bytes);
|
|
|
|
$im->transformImageColorspace(\Imagick::COLORSPACE_SRGB);
|
|
$resolution = $im->getImageGeometry();
|
|
$size = new Vector2($resolution["width"], $resolution["height"]);
|
|
|
|
$pixels = array_fill(0, $size->y, array_fill(0, $size->x, new Color(0, 0, 0)));
|
|
|
|
$iterator = $im->getPixelIterator();
|
|
foreach ($iterator as $row => $p) {
|
|
foreach ($p as $col => $pixel) {
|
|
$c = $pixel->getColor(true);
|
|
$pixels[$row][$col] = new \swf2ass\Color((int)round($c["r"] * 255), (int)round($c["g"] * 255), (int)round($c["b"] * 255), isset($c["a"]) ? (int)round((1 - $c["a"]) * 255) : null);
|
|
}
|
|
}
|
|
//TODO: add transparency
|
|
|
|
return new JPEGBitmapDefinition($element->getAttribute("objectID"), $size, $pixels);
|
|
}
|
|
} |