master
ブランチ master
LittleBeast / src / Std / Lib / Image / Bitmap.php
7 KB、175行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib\Image;
39
40/**
41 * 画素データ(RGBA、各8ビット、左上から行の順)
42 *
43 * 全ての形式はこれに読み込み(decode)、これから書き出す(encode)。
44 * アニメーション(APNG・GIF・WebP)はframesに、画面と同じ大きさに合成したフレームが入る。
45 */
46final class Bitmap {
47 /** 読み込める最大の画素数(RGBAで約100MiB。それ以上はメモリが足りない事が多い) */
48 public const MAX_PIXELS = 25000000;
49
50 public int $width;
51 public int $height;
52 /** 画素(1画素4バイト:R, G, B, A) */
53 public string $data;
54 /** アニメーションのフレーム([['bitmap' => Bitmap, 'delay' => ミリ秒], ...])。静止画は空 */
55 public array $frames = [];
56 /** アニメーションの繰り返し回数(0 = 無限) */
57 public int $loops = 0;
58
59 public function __construct(int $width, int $height, ?string $data = null) {
60 self::check($width, $height);
61 $this->width = $width;
62 $this->height = $height;
63 $this->data = $data ?? str_repeat("\0\0\0\0", $width * $height);
64 if (strlen($this->data) !== $width * $height * 4) throw new \InvalidArgumentException('画素データの大きさが合いません。');
65 }
66
67 /**
68 * 画像の大きさを確認する(読み込む前に、壊れた・大き過ぎるファイルで落ちない様に)
69 */
70 public static function check(int $width, int $height): void {
71 if ($width < 1 || $height < 1) throw new \RuntimeException("画像の大きさが不正です({$width}x{$height})。");
72 if ($width * $height > self::MAX_PIXELS) throw new \RuntimeException("画像が大き過ぎます({$width}x{$height})。");
73 }
74
75 /** 1色で塗った画像 */
76 public static function fill(int $width, int $height, int $r, int $g, int $b, int $a = 255): self {
77 self::check($width, $height);
78 return new self($width, $height, str_repeat(chr($r).chr($g).chr($b).chr($a), $width * $height));
79 }
80
81 /**
82 * 画素を読む
83 *
84 * @return array [r, g, b, a]
85 */
86 public function get(int $x, int $y): array {
87 $o = ($y * $this->width + $x) * 4;
88 return [ord($this->data[$o]), ord($this->data[$o + 1]), ord($this->data[$o + 2]), ord($this->data[$o + 3])];
89 }
90
91 public function set(int $x, int $y, int $r, int $g, int $b, int $a = 255): void {
92 $o = ($y * $this->width + $x) * 4;
93 $this->data[$o] = chr($r);
94 $this->data[$o + 1] = chr($g);
95 $this->data[$o + 2] = chr($b);
96 $this->data[$o + 3] = chr($a);
97 }
98
99 /** 1行分の画素(RGBA) */
100 public function row(int $y): string {
101 return substr($this->data, $y * $this->width * 4, $this->width * 4);
102 }
103
104 /** 全ての画素が不透明か */
105 public function isOpaque(): bool {
106 $len = strlen($this->data);
107 for ($i = 3; $i < $len; $i += 4) if ($this->data[$i] !== "\xff") return false;
108 return true;
109 }
110
111 /** 全ての画素が灰色(R = G = B)か */
112 public function isGray(): bool {
113 $len = strlen($this->data);
114 for ($i = 0; $i < $len; $i += 4) {
115 if ($this->data[$i] !== $this->data[$i + 1] || $this->data[$i] !== $this->data[$i + 2]) return false;
116 }
117 return true;
118 }
119
120 /**
121 * 別の画像を重ねる(はみ出した部分は切る)
122 *
123 * @param bool $blend true:アルファで合成(over)、false:そのまま置き換える(source)
124 */
125 public function draw(Bitmap $src, int $dx, int $dy, bool $blend = true): void {
126 $x0 = max(0, $dx);
127 $x1 = min($this->width, $dx + $src->width);
128 if ($x0 >= $x1) return;
129 for ($sy = max(0, -$dy); $sy < $src->height && $sy + $dy < $this->height; $sy++) {
130 $line = substr($src->data, ($sy * $src->width + $x0 - $dx) * 4, ($x1 - $x0) * 4);
131 $at = (($sy + $dy) * $this->width + $x0) * 4;
132 if ($blend) $line = self::over(substr($this->data, $at, strlen($line)), $line);
133 $this->data = substr_replace($this->data, $line, $at, strlen($line));
134 }
135 }
136
137 /** 範囲を1色にする */
138 public function clear(int $x, int $y, int $w, int $h, int $r = 0, int $g = 0, int $b = 0, int $a = 0): void {
139 $this->draw(self::fill(max(1, $w), max(1, $h), $r, $g, $b, $a), $x, $y, false);
140 }
141
142 /**
143 * RGBAの列のアルファ合成($fgを$bgの上に)
144 */
145 public static function over(string $bg, string $fg): string {
146 // 殆どの画素は完全に不透明か透明なので、その場合は計算しない
147 $len = strlen($fg);
148 $out = $bg;
149 for ($i = 0; $i < $len; $i += 4) {
150 $fa = ord($fg[$i + 3]);
151 if ($fa === 255) {
152 $out[$i] = $fg[$i];
153 $out[$i + 1] = $fg[$i + 1];
154 $out[$i + 2] = $fg[$i + 2];
155 $out[$i + 3] = "\xff";
156 } else if ($fa !== 0) {
157 $ba = ord($bg[$i + 3]);
158 $oa = $fa + intdiv($ba * (255 - $fa) + 127, 255);
159 for ($c = 0; $c < 3; $c++) {
160 $v = (ord($fg[$i + $c]) * $fa * 255 + ord($bg[$i + $c]) * $ba * (255 - $fa)) / (255 * $oa);
161 $out[$i + $c] = chr((int)round($v));
162 }
163 $out[$i + 3] = chr($oa);
164 }
165 }
166 return $out;
167 }
168
169 public function copy(): self {
170 $b = new self($this->width, $this->height, $this->data);
171 $b->frames = $this->frames;
172 $b->loops = $this->loops;
173 return $b;
174 }
175}