PbmCodec::encode()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
c 1
b 0
f 0
nc 7
nop 0
dl 0
loc 28
ccs 0
cts 20
cp 0
crap 30
rs 9.4888
1
<?php
2
3
/**
4
 * This file is part of PhpAidc LabelPrinter package.
5
 *
6
 * © Appwilio (https://appwilio.com)
7
 * © JhaoDa (https://github.com/jhaoda)
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace PhpAidc\LabelPrinter\Emulation;
16
17
final class PbmCodec
18
{
19
    /** @var \Imagick */
20
    private $image;
21
22
    /** @var array */
23
    private $buffer;
24
25
    /** @var int */
26
    private $bytesPerRow;
27
28
    public static function create(\Imagick $image): self
29
    {
30
        return new self($image);
31
    }
32
33
    public function __construct(\Imagick $image)
34
    {
35
        $this->image = $image;
36
37
        $this->bytesPerRow = \intdiv($image->getImageWidth() + 7, 8);
38
39
        $this->buffer = \array_fill(0, $this->bytesPerRow * $image->getImageHeight(), 0);
40
    }
41
42
    public function encode(): string
43
    {
44
        foreach ((new \ImagickPixelIterator($this->image)) as $y => $row) {
45
            $bit = $byte = 0;
46
47
            /** @var \ImagickPixel[] $row */
48
            foreach ($row as $x => $pixel) {
49
                $color = $pixel->getColor();
50
51
                $value = (int) (($color['r'] + $color['g'] + $color['b']) / 3) >> 7;
52
53
                $bit = $x % 8;
54
55
                $byte = ($y * $this->bytesPerRow) + \intdiv($x, 8);
56
57
                if ($value === 0) {
58
                    $this->buffer[$byte] &= ~(1 << (7 - $bit));
59
                } else {
60
                    $this->buffer[$byte] |= (1 << (7 - $bit));
61
                }
62
            }
63
64
            if ($bit !== 7) {
65
                $this->buffer[$byte] ^= (1 << (7 - $bit)) - 1;
66
            }
67
        }
68
69
        return \pack('C*', ...$this->buffer);
70
    }
71
}
72