-
Notifications
You must be signed in to change notification settings - Fork 0
/
nimBMP.nim
888 lines (739 loc) · 25.9 KB
/
nimBMP.nim
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
# BMP Graphics Encoder and Decoder written in Nim
# part of nimPDF sister projects
#
# Copyright (c) 2015-2016 Andri Lim
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#-------------------------------------
import streams, endians, tables, hashes, strutils
const
#set to a default of 96 dpi
DefaultXPelsPerMeter = 3780
DefaultYPelsPerMeter = 3780
defaultPalette = [(7,192'u8,192'u8,192'u8),
(8,192'u8,220'u8,192'u8),
(9,166'u8,202'u8,240'u8),
(246,255'u8,251'u8,240'u8),
(247,160'u8,160'u8,164'u8),
(248,128'u8,128'u8,128'u8),
(249,255'u8,0'u8,0'u8),
(250,0'u8,255'u8,0'u8),
(251,255'u8,255'u8,0'u8),
(252,0'u8,0'u8,255'u8),
(253,255'u8,0'u8,255'u8),
(254,0'u8,255'u8,255'u8),
(255,255'u8,255'u8,255'u8)]
palMaker = [(1,1,1,128,128,128),
(1,1,1,255,255,255),
(3,7,7,32,32,64)]
BMPSignature = "\x42\x4D"
type
BYTE = uint8
WORD = uint16
DWORD = uint32
LONG = int32
BMPCompression* = enum
BC_NONE,
BC_RLE8,
BC_RLE4,
BC_BITFIELDS
BMPHeader = object
fileSize: DWORD
reserved1: WORD
reserved2: WORD
offset: LONG
BMPInfo = object
size: DWORD
width, height: LONG
planes, bitsPerPixel: WORD
compression, imageSize: DWORD
horzResolution, vertResolution: LONG
colorUsed, colorImportant: DWORD
BMPRGBA* {.pure, final.} = object
b*,g*,r*,a*: BYTE #the order must be b,g,r,a!
BMP* = ref object
pixels*: seq[BMPRGBA]
palette*: seq[BMPRGBA]
inverted*: bool
compression*: BMPCompression
bitsPerPixel*: int
width*: int
height*: int
BMPResult*[T] = object
data*: T
width*, height*: int
InputContainer* = string or seq[uint8] or seq[byte]
ScanlineReader = proc(bmp: BMP, input: openArray[byte], row: int)
const
RLE_COMMAND = 0
RLE_ENDOFLINE = 0
RLE_ENDOFBITMAP = 1
RLE_DELTA = 2
proc BMPError(msg: string): ref Exception =
new(result)
result.msg = msg
proc readLE[T: WORD|DWORD|LONG](s: Stream, val: var T): bool =
if s.atEnd(): return false
var tmp: T
if s.readData(addr(tmp), sizeof(T)) != sizeof(T): return false
when T is WORD: littleEndian16(addr(val), addr(tmp))
else: littleEndian32(addr(val), addr(tmp))
result = true
proc readLE[T: BMPHeader|BMPInfo](s: Stream, val: var T) =
for field in fields(val):
if not s.readLE(field):
raise BMPError("error when reading file")
proc readWORD(s: Stream): WORD =
if not s.readLE(result): raise BMPError("error when reading word")
proc readDWORD(s: Stream): DWORD =
if not s.readLE(result): raise BMPError("error when reading dword")
proc skip(s: Stream, nums: int) =
var tmp: char
for i in 0..<nums: tmp = s.readChar()
proc pow(base: int, exponent: int): int =
result = 1
for i in 1..exponent: result *= base
proc numColors(bmp: BMP): int =
if bmp.bitsPerPixel == 32: result = 2.pow(24)
else: result = 2.pow(bmp.bitsPerPixel)
proc fillPalette[T](bmp: BMP, pm: T, idx: int): int =
var i = idx
for L in 0..pm[0]:
for K in 0..pm[1]:
for J in 0..pm[2]:
bmp.palette[i].r = BYTE(J*pm[3])
bmp.palette[i].g = BYTE(K*pm[4])
bmp.palette[i].b = BYTE(L*pm[5])
bmp.palette[i].a = 0
inc i
result = i
proc createStandardPalette(bmp: BMP) =
assert bmp.bitsPerPixel in {1, 4, 8}
if bmp.bitsPerPixel == 1:
for i in 0..1:
bmp.palette[i].r = BYTE(i*255)
bmp.palette[i].g = BYTE(i*255)
bmp.palette[i].b = BYTE(i*255)
bmp.palette[i].a = 0
return
if bmp.bitsPerPixel == 4:
var i = bmp.fillPalette(palMaker[0], 0)
discard bmp.fillPalette(palMaker[1], i)
i = 8
bmp.palette[i].r = 192
bmp.palette[i].g = 192
bmp.palette[i].b = 192
return
if bmp.bitsPerPixel == 8:
discard bmp.fillPalette(palMaker[2], 0)
discard bmp.fillPalette(palMaker[0], 0)
for x in defaultPalette:
let i = x[0]
bmp.palette[i].r = x[1]
bmp.palette[i].g = x[2]
bmp.palette[i].b = x[3]
proc read32bitRow(bmp: BMP, input: openArray[byte], row: int) =
for i in 0..<bmp.width:
let px = row * bmp.width + i
let cx = i * 4
bmp.pixels[px].b = BYTE(input[cx])
bmp.pixels[px].g = BYTE(input[cx+1])
bmp.pixels[px].r = BYTE(input[cx+2])
bmp.pixels[px].a = BYTE(input[cx+3])
proc read24bitRow(bmp: BMP, input: openArray[byte], row: int) =
for i in 0..<bmp.width:
let px = row * bmp.width + i
let cx = i * 3
bmp.pixels[px].b = BYTE(input[cx])
bmp.pixels[px].g = BYTE(input[cx+1])
bmp.pixels[px].r = BYTE(input[cx+2])
proc read8bitRow(bmp: BMP, input: openArray[byte], row: int) =
for i in 0..<bmp.width:
bmp.pixels[row * bmp.width + i] = bmp.palette[input[i].int]
proc read4bitRow(bmp: BMP, input: openArray[byte], row: int) =
var i = 0
var k = 0
while i < bmp.width:
var index = (input[k].int shr 4) and 0x0F
bmp.pixels[row * bmp.width + i] = bmp.palette[index]
inc i
if i < bmp.width: #odd width
index = input[k].int and 0x0F
bmp.pixels[row * bmp.width + i] = bmp.palette[index]
inc i
inc k
proc read1bitRow(bmp: BMP, input: openArray[byte], row: int) =
var
i = 0
j = 0
k = 0
while i < bmp.width:
j = 0
while j < 8 and i < bmp.width:
let index = (input[k].int shr (7 - j)) and 0x01
bmp.pixels[bmp.width * row + i] = bmp.palette[index]
inc i
inc j
inc k
proc getScanlineReader(bmp: BMP): ScanlineReader =
case bmp.bitsPerPixel
of 1: result = read1bitRow
of 4: result = read4bitRow
of 8: result = read8bitRow
of 24: result = read24bitRow
of 32: result = read32bitRow
else: raise BMPError("unavailable scanline reader")
proc readPixels(bmp: BMP, s: Stream) =
let scanlineSize = 4 * ((bmp.width * bmp.bitsPerPixel + 31) div 32)
var scanLine = newSeq[byte](scanlineSize)
let rowReader = bmp.getScanlineReader()
if bmp.inverted:
for row in countdown(bmp.height-1, 0):
if s.readData(scanLine[0].addr, scanlineSize) != scanlineSize:
#raise BMPError("error reading bitmap scanline")
break
bmp.rowReader(scanLine, row)
else:
for row in countup(0, bmp.height-1):
if s.readData(scanLine[0].addr, scanlineSize) != scanlineSize:
#raise BMPError("error reading bitmap scanline")
break
bmp.rowReader(scanLine, row)
proc makeShift(mask: WORD): WORD =
result = 0
var TempShift = mask
while TempShift > WORD(31):
TempShift = TempShift shr 1
inc result
proc readPixels16(bmp: BMP, s: Stream, bytesToSkip: int) =
let scanlineSize = bmp.width * 2
let paddingBytes = (4 - scanlineSize mod 4) mod 4
var BMask: WORD = 31
var GMask: WORD = 992
var RMask: WORD = 31744
if bmp.compression != BC_NONE:
var TMask: WORD
try:
RMask = s.readWORD()
TMask = s.readWORD()
GMask = s.readWORD()
TMask = s.readWORD()
BMask = s.readWORD()
TMask = s.readWORD()
except:
#missing color mask
return
if bytesToSkip > 0: s.skip(bytesToSkip)
let GShift = makeShift(GMask)
let BShift = makeShift(BMask)
let RShift = makeShift(RMask)
template read16bitRow(): untyped =
for i in 0..<bmp.width:
var val = s.readWORD()
let px = int(uint(row) * uint(bmp.width) + uint(i))
bmp.pixels[px].r = BYTE(WORD(8)*((RMask and val) shr RShift))
bmp.pixels[px].g = BYTE(WORD(8)*((GMask and val) shr GShift))
bmp.pixels[px].b = BYTE(WORD(8)*((BMask and val) shr BShift))
s.skip(paddingBytes)
#catch cropped image
try:
if bmp.inverted:
for row in countdown(bmp.height-1, 0): read16bitRow()
else:
for row in countup(0, bmp.height-1): read16bitRow()
except:
discard
proc getScanLine(bmp: BMP, scanLine: int): int =
if bmp.inverted: result = (bmp.height - 1 - scanLine) * bmp.width
else: result = scanLine * bmp.width
proc readPixelsRLE4(bmp: BMP, s: Stream) =
var
bits = 0
statusByte: int
secondByte: int
scanLine = 0
while scanLine < bmp.height:
if s.atEnd(): break
statusByte = s.readChar.ord
if statusByte != RLE_COMMAND:
let count = min(statusByte, bmp.width - bits)
let start = bmp.getScanLine(scanLine)
#Encoded mode
if s.atEnd(): break
secondByte = s.readChar.ord
for i in 0..<count:
if (i and 0x01) != 0: bmp.pixels[start + bits] = bmp.palette[secondByte and 0x0F]
else: bmp.pixels[start + bits] = bmp.palette[(secondByte shr 4) and 0x0F]
inc bits
else:
#Escape mode
if s.atEnd(): break
statusByte = s.readChar.ord
case statusByte
of RLE_ENDOFLINE:
bits = 0
inc scanLine
of RLE_ENDOFBITMAP:
#End of bitmap
return
of RLE_DELTA:
#read the delta values
if s.atEnd(): break
let deltaX = s.readChar.ord
if s.atEnd(): break
let deltaY = s.readChar.ord
#apply them
inc(bits, deltaX)
inc(scanLine, deltaY)
else:
#Absolute mode
let count = min(statusByte, bmp.width - bits)
let start = bmp.getScanLine(scanLine)
for i in 0..<count:
if(i and 0x01) == 0:
if s.atEnd(): break
secondByte = s.readChar.ord
if (i and 0x01) != 0: bmp.pixels[start + bits] = bmp.palette[secondByte and 0x0F]
else: bmp.pixels[start + bits] = bmp.palette[(secondByte shr 4) and 0x0F]
inc bits
#Read pad byte
if((statusByte and 0x03) == 1) or ((statusByte and 0x03) == 2):
if s.atEnd(): break
discard s.readChar.ord
proc readPixelsRLE8(bmp: BMP, s: Stream) =
var
scanLine = 0
bits = 0
statusByte: int
secondByte: int
while scanLine < bmp.height:
if s.atEnd(): return
statusByte = s.readChar.ord
if statusByte == RLE_COMMAND:
if s.atEnd(): return
statusByte = s.readChar.ord
case statusByte
of RLE_ENDOFLINE:
bits = 0
inc scanLine
of RLE_ENDOFBITMAP:
return
of RLE_DELTA:
#read the delta values
if s.atEnd(): return
let deltaX = s.readChar.ord
if s.atEnd(): return
let deltaY = s.readChar.ord
#apply them
inc(bits, deltaX)
inc(scanLine, deltaY)
else:
if scanLine >= bmp.height: return
let count = min(statusByte, bmp.width - bits)
let start = bmp.getScanLine(scanLine)
for i in 0..<count:
if s.atEnd(): return
secondByte = s.readChar.ord
bmp.pixels[start + bits] = bmp.palette[secondByte]
inc bits
#align run length to even number of bytes
if (statusByte and 1) == 1:
if s.atEnd(): return
secondByte = s.readChar.ord
else:
if scanLine >= bmp.height: return
let count = min(statusByte, bmp.width - bits)
let start = bmp.getScanLine(scanLine)
if s.atEnd(): return
secondByte = s.readChar.ord
for i in 0..<count:
bmp.pixels[start + bits] = bmp.palette[secondByte]
inc bits
proc makeShift(mask: DWORD): DWORD =
result = 0
var pos: DWORD = 1
while((pos and mask) == 0) and result < 31:
pos = pos shl 1
inc result
proc readPixels32(bmp: BMP, s: Stream, bytesToSkip: int) =
var
BMask = s.readDWORD()
GMask = s.readDWORD()
RMask = s.readDWORD()
if bytesToSkip > 0: s.skip(bytesToSkip)
let GShift = makeShift(GMask)
let BShift = makeShift(BMask)
let RShift = makeShift(RMask)
let maxR = RMask shr RShift
let maxG = GMask shr GShift
let maxB = BMask shr BShift
template read32bitMasked(): untyped =
for i in 0..<bmp.width:
var val = s.readDWORD()
let px = row * bmp.width + i
let R = ((RMask and val) shr RShift).float / maxR.float
let G = ((GMask and val) shr GShift).float / maxG.float
let B = ((BMask and val) shr BShift).float / maxB.float
bmp.pixels[px].r = BYTE(R * 255.float)
bmp.pixels[px].g = BYTE(G * 255.float)
bmp.pixels[px].b = BYTE(B * 255.float)
#catch cropped image
try:
if bmp.inverted:
for row in countdown(bmp.height-1, 0): read32bitMasked()
else:
for row in countup(0, bmp.height-1): read32bitMasked()
except:
discard
proc decodeBMP*(s: Stream): BMP =
var bmp: BMP
new(bmp)
let signature = s. readStr(2)
var header: BMPHeader
var info: BMPInfo
try:
s.readLE(header)
except:
raise BMPError("error reading BMP header")
try:
s.readLE(info)
except:
raise BMPError("error reading BMP info")
if signature != BMPSignature and info.size != 40:
raise BMPError("signature mismatch") #perhaps only it's signature invalid?
if info.size != 40:
raise BMPError("wrong BMP version, only supported version 3.0")
if header.offset <= 0:
header.offset = LONG(54 + int(info.colorUsed) * 4)
bmp.width = info.width
bmp.height = info.height
bmp.inverted = true
if info.height < 0:
bmp.inverted = false
bmp.height = -1 * info.height
bmp.bitsPerPixel = int(info.bitsPerPixel)
if bmp.bitsPerPixel notin {1, 4, 8, 16, 24, 32}:
raise BMPError("unsupported bitsPerPixel: " & $bmp.bitsPerPixel)
if info.compression > 3.DWORD: info.compression = 0.DWORD #really bad compression
bmp.compression = BMPCompression(info.compression)
if bmp.compression notin {BC_NONE, BC_RLE4, BC_RLE8, BC_BITFIELDS}:
raise BMPError("unsupported compression: " & $info.compression)
if bmp.compression in {BC_NONE, BC_BITFIELDS}:
let scanlineSize = 4'i64 * ((int64(info.width) * int64(info.bitsPerPixel) + 31'i64) div 32'i64)
let dataSize = scanlineSize * int64(info.height)
if info.imageSize == 0:
info.imageSize = DWORD(dataSize)
if dataSize + int64(header.offset) > int64(header.fileSize):
raise BMPError("invalid dataSize")
if dataSize > int64(info.imageSize):
raise BMPError("invalid width x height")
if (bmp.compression == BC_BITFIELDS) and bmp.bitsPerPixel notin {16, 32}:
raise BMPError("Bitfields Compression only for 16, 32 bits")
if bmp.compression == BC_RLE8 and bmp.bitsPerPixel != 8:
if bmp.bitsPerPixel == 4: bmp.compression = BC_RLE4 #try with this
else: bmp.compression = BC_NONE
#raise BMPError("RLE8 Compression only for 8 bits")
if bmp.compression == BC_RLE4 and bmp.bitsPerPixel != 4:
if bmp.bitsPerPixel == 8: bmp.compression = BC_RLE8 #try with this
else: bmp.compression = BC_NONE
#raise BMPError("RLE4 Compression only for 4 bits")
#read palette
if bmp.bitsPerPixel < 16:
#54 = sizeof BMPInfo + sizeof BMPHeader + signature
let paletteSize = min(int((header.offset - 54) div 4), 2.pow(bmp.bitsPerPixel))
let numColors = bmp.numColors() #max paletteSize
bmp.palette = newSeq[BMPRGBA](numColors)
bmp.createStandardPalette()
for n in 0..<paletteSize:
if s.readData(addr(bmp.palette[n]), 4) != 4:
raise BMPError("error when reading palette")
let BLACK = BMPRGBA(r: 0, g: 0, b: 0, a: 0)
for n in paletteSize..<numColors: bmp.palette[n] = BLACK
var bytesToSkip = int(header.offset - 54)
if bmp.bitsPerPixel < 16: bytesToSkip -= 4 * 2.pow(bmp.bitsPerPixel)
if bmp.bitsPerPixel in {16, 32} and bmp.compression == BC_BITFIELDS: bytesToSkip -= 3 * 4
if bytesToSkip < 0: bytesToSkip = 0
if bytesToSkip > 0 and bmp.compression != BC_BITFIELDS: s.skip(bytesToSkip)
if bmp.width < 0: bmp.width = -1 * bmp.width #another bad value
bmp.pixels = newSeq[BMPRGBA](bmp.width * bmp.height)
if bmp.bitsPerPixel == 16: bmp.readPixels16(s, bytesToSkip)
else:
if bmp.compression == BC_BITFIELDS: bmp.readPixels32(s, bytesToSkip)
elif bmp.compression == BC_RLE4: bmp.readPixelsRLE4(s)
elif bmp.compression == BC_RLE8: bmp.readPixelsRLE8(s)
else: bmp.readPixels(s)
s.close()
result = bmp
proc loadBMP*(fileName: string): BMP =
try:
var s = newFileStream(fileName, fmRead)
if s == nil: return nil
result = s.decodeBMP()
s.close()
except:
debugEcho fileName, " ", getCurrentExceptionMsg()
result = nil
template construct(x: typedesc[string], size: int): untyped = newString(size)
template construct(x: typedesc[seq[uint8]], size: int): untyped = newSeq[uint8](size)
template construct(x: typedesc[seq[byte]], size: int): untyped = newSeq[byte](size)
template getValueT(x: typedesc[string]): typedesc = char
template getValueT(x: typedesc[seq[uint8]]): typedesc = uint8
template getValueT(x: typedesc[seq[byte]]): typedesc = byte
proc convertTo32Bit*[T](bmp: BMP, res: var BMPResult[T]) =
type ValueT = getValueT(T)
let numPixels = bmp.width * bmp.height
for i in 0..<numPixels:
let px = i * 4
res.data[px + 0] = ValueT(bmp.pixels[i].r)
res.data[px + 1] = ValueT(bmp.pixels[i].g)
res.data[px + 2] = ValueT(bmp.pixels[i].b)
res.data[px + 3] = ValueT(bmp.pixels[i].a)
proc convertTo24Bit*[T](bmp: BMP, res: var BMPResult[T]) =
type ValueT = getValueT(T)
let numPixels = bmp.width * bmp.height
for i in 0..<numPixels:
let px = i * 3
res.data[px + 0] = ValueT(bmp.pixels[i].r)
res.data[px + 1] = ValueT(bmp.pixels[i].g)
res.data[px + 2] = ValueT(bmp.pixels[i].b)
proc convertTo8Bit*[T](bmp: BMP, res: var BMPResult[T]) =
type ValueT = getValueT(T)
let numPixels = bmp.width * bmp.height
for i in 0..<numPixels:
var p = bmp.pixels[i]
res.data[i] = ValueT((p.r.int*77 + p.g.int*150 + p.b.int*29) shr 8)
proc convert*[T](bmp: BMP, bitsPerPixel: int): BMPResult[T] =
assert bitsPerPixel in {8, 24, 32}
result.data = construct(T, bmp.width * bmp.height * bitsPerPixel div 8)
result.width = bmp.width
result.height = bmp.height
case bitsPerPixel
of 8 : convertTo8Bit[T](bmp, result)
of 24: convertTo24Bit[T](bmp, result)
of 32: convertTo32Bit[T](bmp, result)
else : convertTo24Bit[T](bmp, result)
proc loadBMP32Aux[T](fileName: string): BMPResult[T] =
var bmp = loadBMP(fileName)
if bmp != nil: result = convert[T](bmp, 32)
proc loadBMP24Aux[T](fileName: string): BMPResult[T] =
var bmp = loadBMP(fileName)
if bmp != nil: result = convert[T](bmp, 24)
proc loadBMP8Aux[T](fileName: string): BMPResult[T] =
var bmp = loadBMP(fileName)
if bmp != nil: result = convert[T](bmp, 8)
template loadBMP32*(fileName: string, T: typedesc): untyped =
loadBMP32Aux[T](fileName)
template loadBMP24*(fileName: string, T: typedesc): untyped =
loadBMP24Aux[T](fileName)
template loadBMP8*(fileName: string, T: typedesc): untyped =
loadBMP8Aux[T](fileName)
template loadBMP32*(fileName: string): untyped =
loadBMP32Aux[string](fileName)
template loadBMP24*(fileName: string): untyped =
loadBMP24Aux[string](fileName)
template loadBMP8*(fileName: string): untyped =
loadBMP8Aux[string](fileName)
type
ConvertT = proc(p: var BMPRGBA, input: openArray[byte], px: int)
EncoderT = proc (bmp: BMPEncoder, input: openArray[byte], output: var openArray[byte], w, h: int)
BMPEncoder = object
bitsPerPixel: int
scanLineSize: int
colors: OrderedTable[BMPRGBA, int]
pixels: seq[byte]
cvt: ConvertT
encoder: EncoderT
proc hash*(c: BMPRGBA): Hash =
var h: Hash = 0
h = h !& ord(c.r)
h = h !& ord(c.g)
h = h !& ord(c.b)
h = h !& ord(c.a)
proc pixelFromGray8(p: var BMPRGBA, input: openArray[byte], px: int) =
p.r = BYTE(input[px])
p.g = BYTE(input[px])
p.b = BYTE(input[px])
proc pixelFromRGB24(p: var BMPRGBA, input: openArray[byte], px: int) =
let y = px * 3
p.r = BYTE(input[y])
p.g = BYTE(input[y + 1])
p.b = BYTE(input[y + 2])
proc pixelFromRGB32(p: var BMPRGBA, input: openArray[byte], px: int) =
let y = px * 4
p.r = BYTE(input[y])
p.g = BYTE(input[y + 1])
p.b = BYTE(input[y + 2])
p.a = BYTE(input[y + 3])
proc pixelFromNoColor(p: var BMPRGBA, input: openArray[byte], px: int) =
discard
proc getCvt(bitsPerPixel: int): ConvertT =
case bitsPerPixel
of 8: result = pixelFromGray8
of 24: result = pixelFromRGB24
of 32: result = pixelFromRGB32
else: result = pixelFromNoColor
proc countColors(input: openArray[byte], w, h, bitsPerPixel: int, colors: var OrderedTable[BMPRGBA, int]): int =
let numPixels = w * h
assert bitsPerPixel in {8, 24, 32}
var
p: BMPRGBA
cvt = getCvt(bitsPerPixel)
numColors = 0
for px in 0..<numPixels:
cvt(p, input, px)
if not colors.hasKey(p):
if numColors < 256:
colors[p] = numColors
inc numColors
if numColors >= 257: break
result = numColors
proc encode1Bit(bmp: BMPEncoder, input: openArray[byte], output: var openArray[byte], w, h: int) =
var
px = 0
p: BMPRGBA
for row in countdown(h - 1, 0):
var x = 0
var y = row * bmp.scanLineSize
while x < w:
var z = 0
var t = 0
while z < 8 and x < w:
bmp.cvt(p, input, px)
t = t or ((bmp.colors[p] and 0x01) shl (7 - z))
inc px
inc z
inc x
output[y] = byte(t)
inc y
proc encode4Bit(bmp: BMPEncoder, input: openArray[byte], output: var openArray[byte], w, h: int) =
var
px = 0
p: BMPRGBA
for row in countdown(h - 1, 0):
let start = row * bmp.scanLineSize
for x in 0..<w:
let y = start + (x div 2)
bmp.cvt(p, input, px)
inc px
if (x mod 2) == 0:
output[y] = byte((bmp.colors[p] and 0x0F) shl 4)
else:
output[y] = byte(output[y].int or (bmp.colors[p] and 0x0F))
proc encode8Bit(bmp: BMPEncoder, input: openArray[byte], output: var openArray[byte], w, h: int) =
var
px = 0
p: BMPRGBA
for row in countdown(h - 1, 0):
let y = row * bmp.scanLineSize
for x in 0..<w:
bmp.cvt(p, input, px)
output[y + x] = byte(bmp.colors[p])
inc px
proc encode24Bit(bmp: BMPEncoder, input: openArray[byte], output: var openArray[byte], w, h: int) =
var
px = 0
p: BMPRGBA
for row in countdown(h - 1, 0):
let start = row * bmp.scanLineSize
for x in 0..<w:
let y = start + x * 3
bmp.cvt(p, input, px)
output[y] = byte(p.b)
output[y + 1] = byte(p.g)
output[y + 2] = byte(p.r)
inc px
proc autoChooseColor(input: openArray[byte], w, h, bitsPerPixel: int): BMPEncoder =
result.cvt = getCvt(bitsPerPixel)
result.colors = initOrderedTable[BMPRGBA, int]()
let numColors = countColors(input, w, h, bitsPerPixel, result.colors)
if numColors <= 2:
result.bitsPerPixel = 1
result.encoder = encode1Bit
elif numColors <= 16:
result.bitsPerPixel = 4
result.encoder = encode4Bit
elif numColors <= 256:
result.bitsPerPixel = 8
result.encoder = encode8Bit
else:
result.bitsPerPixel = 24
result.encoder = encode24Bit
result.scanlineSize = 4 * ((w * result.bitsPerPixel + 31) div 32)
proc writeLE[T: WORD|DWORD|LONG](s: Stream, val: T) =
var
value: T
tmp = val
when T is WORD: littleEndian16(addr(value), addr(tmp))
else: littleEndian32(addr(value), addr(tmp))
s.writeData(addr(value), sizeof(T))
proc writeLE[T: BMPHeader|BMPInfo](s: Stream, val: T) =
for field in fields(val): s.writeLE(field)
proc encodeBMP*(s: Stream, input: openArray[byte], w, h, bitsPerPixel: int) =
if bitsPerPixel notin {8,24,32}:
raise BMPError("unsupported bitsPerPixel: " & $bitsPerPixel)
let expectedLen = ((bitsPerPixel div 8) * w * h)
if input.len < expectedLen:
raise BMPError("invalid input length, expected " & $expectedLen & " got " & $input.len)
var bmp = autoChooseColor(input, w, h, bitsPerPixel)
let scanlineSize = 4 * ((w * bmp.bitsPerPixel + 31) div 32)
let dataSize = scanlineSize * h
let offset = 54 + bmp.colors.len * 4
var header: BMPHeader
header.fileSize = DWORD(offset + dataSize)
header.reserved1 = WORD(0)
header.reserved2 = WORD(0)
header.offset = LONG(offset)
var info: BMPInfo
info.size = 40
info.width = LONG(w)
info.height = LONG(h)
info.planes = 1
info.bitsPerPixel = WORD(bmp.bitsPerPixel)
info.compression = DWORD(BC_NONE)
info.imageSize = DWORD(dataSize)
info.horzResolution = DefaultXPelsPerMeter
info.vertResolution = DefaultYPelsPerMeter
info.colorUsed = DWORD(bmp.colors.len)
info.colorImportant = 0
s.write BMPSignature
s.writeLE header
s.writeLE info
for k in keys(bmp.colors):
var tmp = k
s.writeData(addr(tmp), 4)
var output = newSeq[byte](bmp.scanlineSize * h)
bmp.encoder(bmp, input, output, w, h)
s.writeData(output[0].unsafeAddr, output.len)
template makeOpenArray(p: pointer, T: type, len: int): auto =
toOpenArray(cast[ptr UncheckedArray[T]](p), 0, len - 1)
proc encodeBMP*(s: Stream, input: InputContainer, w, h, bitsPerPixel: int) {.inline.} =
s.encodeBMP(makeOpenArray(input[0].unsafeAddr, byte, input.len), w, h, bitsPerPixel)
proc saveBMP*(fileName: string, input: openArray[byte], w, h: int, bpp: static[int]) =
var s = newFileStream(fileName, fmWrite)
s.encodeBMP(input, w, h, bpp)
s.close()
template saveBMP*(fileName: string, input: InputContainer, w, h: int, bpp: static[int]) =
saveBMP(fileName, makeOpenArray(input[0].unsafeAddr, byte, input.len), w, h, bpp)
proc saveBMP32*(fileName: string, input: InputContainer, w, h: int) {.inline.} =
saveBMP(fileName, input, w, h, 32)
proc saveBMP24*(fileName: string, input: InputContainer, w, h: int) {.inline.} =
saveBMP(fileName, input, w, h, 24)
proc saveBMP8*(fileName: string, input: InputContainer, w, h: int) {.inline.} =
saveBMP(fileName, input, w, h, 8)