PbmCodec   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 53
ccs 0
cts 30
cp 0
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 28 5
A create() 0 3 1
A __construct() 0 7 1
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