-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitmap_file.dart
More file actions
501 lines (443 loc) · 14.4 KB
/
Copy pathbitmap_file.dart
File metadata and controls
501 lines (443 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import 'dart:collection';
import 'dart:convert';
import 'dart:typed_data';
enum ColorModel { rgba, bgra, argb, abgr }
class BitmapFile {
final BitmapFileHeader header;
final BitmapInfo info;
/// ARGB format.
List<int> _pixels;
BitmapFile._(this.header, this.info, ByteBuffer pixelArray) {
_pixels = _parsePixels(pixelArray).toList();
}
factory BitmapFile.fromBuffer(ByteBuffer buffer) {
final header = BitmapFileHeader.fromBytes(
buffer.asByteData(0, BitmapFileHeader.structureSize),
);
final info = BitmapInfo.fromBytes(buffer.asByteData(
BitmapFileHeader.structureSize,
header.offBits - BitmapFileHeader.structureSize,
));
return BitmapFile._(
header,
info,
buffer.asUint8List().sublist(header.offBits).buffer,
);
}
Uint8List getPixels8888([
ColorModel model = ColorModel.bgra,
bool topDown = false,
]) {
final formed = _getPixelColorBy(model).toList();
final stride = info.header.compression == BICompression.rle4 ||
info.header.compression == BICompression.rle8
? info.header.width
: info.header.paddedWidth;
final paddingSize = info.header.paddedWidth - info.header.width;
final clipped = List.generate(
info.header.unsignedHeight,
(index) {
final start = index * stride * 4;
return formed.sublist(start, start + info.header.width * 4)
..addAll(List.filled(paddingSize * 4, 0));
},
);
Iterable<int> pixels;
if (topDown) {
pixels = info.header.height < 0
? clipped.reversed.expand((element) => element)
: clipped.expand((element) => element);
} else {
pixels = info.header.height < 0
? clipped.expand((element) => element)
: clipped.reversed.expand((element) => element);
}
return Uint8List.fromList(pixels.toList());
}
Uint32List getPixels32([
ColorModel model = ColorModel.bgra,
bool topDown = false,
]) {
final pixels8888 = getPixels8888();
final pixels32 = List.generate(pixels8888.length ~/ 4,
(index) => pixels8888.sublist(index * 4, index * 4 + 4))
.expand(
(element) => [element[0] | element[1] | element[2] | element[3]])
.toList();
return Uint32List.fromList(pixels32);
}
Iterable<int> _parsePixels(ByteBuffer buffer) {
switch (info.header.bitCount) {
case 0:
return [];
case 1:
return buffer.asUint8List().expand((pixel) => [
info.colors[(pixel >> 7) & 1].argb,
info.colors[(pixel >> 6) & 1].argb,
info.colors[(pixel >> 5) & 1].argb,
info.colors[(pixel >> 4) & 1].argb,
info.colors[(pixel >> 3) & 1].argb,
info.colors[(pixel >> 2) & 1].argb,
info.colors[(pixel >> 1) & 1].argb,
info.colors[pixel & 1].argb,
]);
case 4:
if (info.header.compression == BICompression.rle4) {
return _decodeRLE(buffer.asUint8List())
.map((pixel) => info.colors[pixel].argb);
}
return buffer.asUint8List().expand((pixel) => [
info.colors[(pixel >> 4) & 0xf].argb,
info.colors[pixel & 0xf].argb,
]);
case 8:
if (info.header.compression == BICompression.rle8) {
return _decodeRLE(buffer.asUint8List())
.map((pixel) => info.colors[pixel].argb);
}
return buffer.asUint8List().map((pixel) => info.colors[pixel].argb);
case 16:
return buffer.asUint16List().map((pixel) {
final isBitField = info.header.compression == BICompression.bitFields;
// Default color masks for 16bpp.
// 0x7c00 = 0111 1100 0000 0000 (red)
// 0x3e0 = 0000 0011 1110 0000 (green)
// 0x1f = 0000 0000 0001 1111 (blue)
final maskR = isBitField ? info.redMask : 0x7c00;
final maskG = isBitField ? info.greenMask : 0x3e0;
final maskB = isBitField ? info.blueMask : 0x1f;
final rgb = _getColorFromBitMasks(pixel, maskR, maskG, maskB);
return 0xff000000 | (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
});
case 24:
return buffer.asUint8List().fold<List<List<int>>>(
[[]],
(bgrList, value) => bgrList.last.length < 3
? (bgrList..last.add(value))
: (bgrList..add([value])),
).map(
(pixel) => 0xff000000 | pixel[2] << 16 | pixel[1] << 8 | pixel[0],
);
case 32:
return buffer.asUint32List().map((pixel) {
final isBitField = info.header.compression == BICompression.bitFields;
if (isBitField) {
final rgb = _getColorFromBitMasks(
pixel,
info.redMask,
info.greenMask,
info.blueMask,
);
return 0xff000000 | (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
} else {
return 0xff000000 | pixel;
}
});
default:
throw Exception('Unsupported bit count (${info.header.bitCount}).');
}
}
List<int> _decodeRLE(Uint8List bytes) {
if (info.header.compression != BICompression.rle4 &&
info.header.compression != BICompression.rle8) {
throw ArgumentError.value(
info.header.compression,
'BICompression',
'The bitmap file was not compressed with RLE, but tried to decoding RLE compression.',
);
}
final pixels = <int>[];
final compressed = Queue<int>.from(bytes);
while (compressed.isNotEmpty) {
final first = compressed.removeFirst();
final second = compressed.removeFirst();
if (first == 0) {
if (second == 0) {
// End of line.
pixels.addAll(List.filled(pixels.length % info.header.width, 0));
} else if (second == 1) {
// End of bitmap.
break;
} else if (second == 2) {
// Delta offset.
final offsetX = compressed.removeFirst();
final offsetY = compressed.removeFirst();
pixels.addAll(List.filled(offsetX + offsetY * info.header.width, 0));
} else {
// Apsolute mode.
final temp = <int>[];
if (info.header.compression == BICompression.rle8) {
final wordBoundedLength = (second / 2).ceil() * 2;
for (var i = 0; i < wordBoundedLength; i++) {
temp.add(compressed.removeFirst());
}
} else if (info.header.compression == BICompression.rle4) {
final byteLength = (second / 2).ceil();
final wordBoundedLength = (byteLength / 2).ceil() * 2;
for (var i = 0; i < wordBoundedLength; i++) {
final byte = compressed.removeFirst();
temp.addAll([(byte >> 4) & 0xf, byte & 0xf]);
}
}
pixels.addAll(temp.take(second));
}
} else {
// Encoded mode.
if (info.header.compression == BICompression.rle8) {
for (var i = 0; i < first; i++) {
pixels.add(second);
}
} else if (info.header.compression == BICompression.rle4) {
var orderSwitcher = 1;
for (var i = 0; i < first; i++) {
final pixel =
orderSwitcher > 0 ? (second >> 4) & 0xf : second & 0xf;
pixels.add(pixel);
orderSwitcher *= -1;
}
}
}
}
return pixels;
}
static int _makeSolidMask(int length) {
int mask = 0;
while (length > 0) {
mask |= 1 << --length;
}
return mask;
}
/// Returns color value [List] order by red, green, blue.
static List<int> _getColorFromBitMasks(
int pixel,
int maskR,
int maskG,
int maskB,
) {
var offsetR = 0;
var offsetG = 0;
var offsetB = 0;
var bitCntR = 0;
var bitCntG = 0;
var bitCntB = 0;
// Specify offsets for make ARGB model.
while (maskR > 0) {
if ((maskR & (1 << offsetR)) == 0) {
offsetR++;
} else if (((maskR >> offsetR) & (1 << bitCntR)) != 0) {
bitCntR++;
} else {
break;
}
}
while (maskG > 0) {
if ((maskG & (1 << offsetG)) == 0) {
offsetG++;
} else if ((maskG >> offsetG) & (1 << bitCntG) != 0) {
bitCntG++;
} else {
break;
}
}
while (maskB > 0) {
if ((maskB & (1 << offsetB)) == 0) {
offsetB++;
} else if ((maskB >> offsetB) & (1 << bitCntB) != 0) {
bitCntB++;
} else {
break;
}
}
// x = max value for bitCntR or bitCntG or bitCntB.
// y = max value for 8-bit.
// n = value in x.
// m = value in y.
// n / x = m / y
// m = ny / x
final red = bitCntR == 0
? 0
: (((pixel & maskR) >> offsetR) * 0xff) / _makeSolidMask(bitCntR);
final green = bitCntG == 0
? 0
: (((pixel & maskG) >> offsetG) * 0xff) / _makeSolidMask(bitCntG);
final blue = bitCntB == 0
? 0
: (((pixel & maskB) >> offsetB) * 0xff) / _makeSolidMask(bitCntB);
return [red.round(), green.round(), blue.round()];
}
Iterable<int> _getPixelColorBy(ColorModel model) {
switch (model) {
case ColorModel.rgba:
return _pixels.expand((element) => [
(element & 0x00ff0000) >> 16,
(element & 0x0000ff00) >> 8,
element & 0x000000ff,
(element & 0xff000000) >> 24,
]);
break;
case ColorModel.bgra:
return _pixels.expand((element) => [
element & 0x000000ff,
(element & 0x0000ff00) >> 8,
(element & 0x00ff0000) >> 16,
(element & 0xff000000) >> 24,
]);
break;
case ColorModel.argb:
return _pixels.expand((element) => [
(element & 0xff000000) >> 24,
(element & 0x00ff0000) >> 16,
(element & 0x0000ff00) >> 8,
element & 0x000000ff,
]);
break;
case ColorModel.abgr:
return _pixels.expand((element) => [
(element & 0xff000000) >> 24,
element & 0x000000ff,
(element & 0x0000ff00) >> 8,
(element & 0x00ff0000) >> 16,
]);
break;
default:
throw Exception('Cannot rearrange bytes by null.');
}
}
}
class BitmapFileHeader {
static const int structureSize = 14;
final String type;
final int size;
final int reserved1;
final int reserved2;
final int offBits;
const BitmapFileHeader._({
this.type,
this.size,
this.reserved1,
this.reserved2,
this.offBits,
}) : assert(type == 'BM'),
assert(reserved1 == 0),
assert(reserved2 == 0);
factory BitmapFileHeader.fromBytes(ByteData bytes) => BitmapFileHeader._(
type: ascii.decode([bytes.getUint8(0), bytes.getUint8(1)]),
size: bytes.getUint32(2, Endian.little),
reserved1: bytes.getUint16(6, Endian.little),
reserved2: bytes.getUint16(8, Endian.little),
offBits: bytes.getUint32(10, Endian.little),
);
}
enum BICompression { rgb, rle8, rle4, bitFields, jpeg, png }
class BitmapInfo {
final BitmapInfoHeader header;
final List<RGBQuad> colors;
final int redMask;
final int greenMask;
final int blueMask;
const BitmapInfo._(
this.header,
this.colors, {
this.redMask,
this.greenMask,
this.blueMask,
});
factory BitmapInfo.fromBytes(ByteData bytes) {
final header = BitmapInfoHeader.fromBytes(bytes);
final colors = <RGBQuad>[];
var offset = header.size;
int redMask;
int greenMask;
int blueMask;
if (header.compression == BICompression.bitFields &&
(header.bitCount == 16 || header.bitCount == 32)) {
redMask = bytes.getUint32(offset, Endian.little);
offset += 4;
greenMask = bytes.getUint32(offset, Endian.little);
offset += 4;
blueMask = bytes.getUint32(offset, Endian.little);
offset += 4;
}
for (; offset < bytes.lengthInBytes; offset += 4) {
colors.add(
RGBQuad.fromBytes(
bytes.buffer.asByteData(offset + bytes.offsetInBytes, 4),
),
);
}
return BitmapInfo._(
header,
colors,
redMask: redMask,
greenMask: greenMask,
blueMask: blueMask,
);
}
}
class BitmapInfoHeader {
final int size;
final int width;
final int height;
final int planes;
final int bitCount;
final BICompression compression;
final int sizeImage;
final int xPelsPerMeter;
final int yPelsPerMeter;
final int clrUsed;
final int clrImportant;
BitmapInfoHeader._({
this.size,
this.width,
this.height,
this.planes,
this.bitCount,
this.compression,
this.sizeImage,
this.xPelsPerMeter,
this.yPelsPerMeter,
this.clrUsed,
this.clrImportant,
}) : assert(height < 0
? (compression == BICompression.rgb ||
compression == BICompression.bitFields)
: true),
assert(planes == 1),
assert([0, 1, 4, 8, 16, 24, 32].contains(bitCount)) {
if (size != 40) {
throw Exception('Unsupported Bitmap version. Only support version 3.');
}
}
factory BitmapInfoHeader.fromBytes(ByteData bytes) => BitmapInfoHeader._(
size: bytes.getUint32(0, Endian.little),
width: bytes.getInt32(4, Endian.little),
height: bytes.getInt32(8, Endian.little),
planes: bytes.getUint16(12, Endian.little),
bitCount: bytes.getUint16(14, Endian.little),
compression: BICompression.values[bytes.getUint32(16, Endian.little)],
sizeImage: bytes.getUint32(20, Endian.little),
xPelsPerMeter: bytes.getUint32(24, Endian.little),
yPelsPerMeter: bytes.getUint32(28, Endian.little),
clrUsed: bytes.getUint32(32, Endian.little),
clrImportant: bytes.getUint32(36, Endian.little),
);
int get paddedWidth => (width * bitCount) % 32 == 0
? width
: ((((width * bitCount) / 32).ceil()) * 32) ~/ bitCount;
int get unsignedHeight => height < 0 ? -height : height;
}
class RGBQuad {
final int blue;
final int green;
final int red;
final int reserved;
const RGBQuad._({this.blue, this.green, this.red, this.reserved})
: assert(reserved == 0);
factory RGBQuad.fromBytes(ByteData bytes) => RGBQuad._(
blue: bytes.getUint8(0),
green: bytes.getUint8(1),
red: bytes.getUint8(2),
reserved: bytes.getUint8(3),
);
int get argb => 0xff000000 | red << 16 | green << 8 | blue;
}