-
Notifications
You must be signed in to change notification settings - Fork 1
/
QrCode.cs
1373 lines (1202 loc) · 59.7 KB
/
QrCode.cs
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* QR code generator library (.NET)
*
* Copyright (c) Manuel Bleichenbacher (MIT License)
* https://github.com/manuelbl/QrCodeGenerator
* Copyright (c) Project Nayuki (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
* Copyright (c) [email protected] (MIT License)
* https://ardeshirv.github.io/ArdeshirV.Utility.QrCode/
* Downgrade to C# 2.0 by ArdeshirV
*
* 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
namespace ArdeshirV.Tools.QrCode
{
/// <summary>
/// Represents a QR code containing text or binary data.
/// <para>
/// Instances of this class represent an immutable square grid of black and white pixels
/// (called <i>modules</i> by the QR code specification).
/// Static factory methods are provided to create QR codes from text or binary data.
/// Some of the methods provide detailed control about the encoding parameters such a QR
/// code size (called <i>version</i> by the standard), error correction level and mask.
/// </para>
/// <para>
/// QR codes are a type of two-dimensional barcodes, invented by Denso Wave and
/// described in the ISO/IEC 18004 standard.
/// </para>
/// <para>
/// This class covers the QR Code Model 2 specification, supporting all versions (sizes)
/// from 1 to 40, all 4 error correction levels, and 4 character encoding modes.</para>
/// </summary>
/// <remarks>
/// <para>
/// To create a QR code instance:
/// </para>
/// <ul>
/// <li>High level: Take the payload data and call <see cref="EncodeText(string, Ecc)"/>
/// or <see cref="EncodeBinary(byte[], Ecc)"/>.</li>
/// <li>Mid level: Custom-make a list of <see cref="QrSegment"/> instances and call
/// <see cref="EncodeSegments"/></li>
/// <li>Low level: Custom-make an array of data codeword bytes (including segment headers and
/// final padding, excluding error correction codewords), supply the appropriate version number,
/// and call the <see cref="QrCode(int, Ecc, byte[], int)"/>.</li>
/// </ul>
/// </remarks>
/// <seealso cref="QrSegment"/>
public class QrCode
{
#region Static factory functions (high level)
/// <summary>
/// Creates a QR code representing the specified text using the specified error correction level.
/// <para>
/// As a conservative upper bound, this function is guaranteed to succeed for strings with up to 738
/// Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
/// QR code version (size) is automatically chosen. The resulting ECC level will be higher than the one
/// specified if it can be achieved without increasing the size (version).
/// </para>
/// </summary>
/// <param name="text">The text to be encoded. The full range of Unicode characters may be used.</param>
/// <param name="ecl">The minimum error correction level to use.</param>
/// <returns>The created QR code instance representing the specified text.</returns>
/// <exception cref="ArgumentNullException"><paramref name="text"/> or <paramref name="ecl"/> is <c>null</c>.</exception>
/// <exception cref="DataTooLongException">The text is too long to fit in the largest QR code size (version)
/// at the specified error correction level.</exception>
public static QrCode EncodeText(string text, Ecc ecl)
{
Objects.RequireNonNull(text);
Objects.RequireNonNull(ecl);
List<QrSegment> segs = QrSegment.MakeSegments(text);
return EncodeSegments(segs, ecl);
}
/// <summary>
/// Creates a QR code representing the specified binary data using the specified error correction level.
/// <para>
/// This function encodes the data in the binary segment mode. The maximum number of
/// bytes allowed is 2953. The smallest possible QR code version is automatically chosen.
/// The resulting ECC level will be higher than the one specified if it can be achieved without increasing the size (version).
/// </para>
/// </summary>
/// <param name="data">The binary data to encode.</param>
/// <param name="ecl">The minimum error correction level to use.</param>
/// <returns>The created QR code representing the specified data.</returns>
/// <exception cref="ArgumentNullException"><paramref name="data"/> or <paramref name="ecl"/> is <c>null</c>.</exception>
/// <exception cref="DataTooLongException">The specified data is too long to fit in the largest QR code size (version)
/// at the specified error correction level.</exception>
public static QrCode EncodeBinary(byte[] data, Ecc ecl)
{
Objects.RequireNonNull(data);
Objects.RequireNonNull(ecl);
QrSegment seg = QrSegment.MakeBytes(data);
List<QrSegment> segs = new List<QrSegment>();
segs.Add(seg);
return EncodeSegments(segs, ecl);
}
#endregion
#region Static factory functions (mid level)
/// <summary>
/// Creates a QR code representing the specified segments with the specified encoding parameters.
/// <para>
/// The QR code mask is usually automatically chosen. It can be explicitly set with the <paramref name="mask"/>
/// parameter by using a value between 0 to 7 (inclusive). -1 is for automatic mode (which may be slow).
/// </para>
/// <para>
/// This function allows the user to create a custom sequence of segments that switches
/// between modes (such as alphanumeric and byte) to encode text in less space and gives full control over all
/// encoding paramters.
/// </para>
/// </summary>
/// <remarks>
/// This is a mid-level API; the high-level APIs are <see cref="EncodeText(string, Ecc)"/>
/// and <see cref="EncodeBinary(byte[], Ecc)"/>.
/// </remarks>
/// <param name="segments">The segments to encode.</param>
/// <param name="ecl">The minimal or fixed error correction level to use .</param>
/// <returns>The created QR code representing the segments.</returns>
/// <exception cref="ArgumentNullException"><paramref name="segments"/>, any list element, or <paramref name="ecl"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">1 ≤ minVersion ≤ maxVersion ≤ 40
/// or -1 ≤ mask ≤ 7 is violated.</exception>
/// <exception cref="DataTooLongException">The segments are too long to fit in the largest QR code size (version)
/// at the specified error correction level.</exception>
public static QrCode EncodeSegments(List<QrSegment> segments, Ecc ecl)
{
return EncodeSegments(segments, ecl, MinVersion, MaxVersion, -1, true);
}
/// <summary>
/// Creates a QR code representing the specified segments with the specified encoding parameters.
/// <para>
/// The smallest possible QR code version (size) is used. The range of versions can be
/// restricted by the <paramref name="minVersion"/> parameter.
/// </para>
/// <para>
/// The QR code mask is usually automatically chosen. It can be explicitly set with the <paramref name="mask"/>
/// parameter by using a value between 0 to 7 (inclusive). -1 is for automatic mode (which may be slow).
/// </para>
/// <para>
/// This function allows the user to create a custom sequence of segments that switches
/// between modes (such as alphanumeric and byte) to encode text in less space and gives full control over all
/// encoding paramters.
/// </para>
/// </summary>
/// <remarks>
/// This is a mid-level API; the high-level APIs are <see cref="EncodeText(string, Ecc)"/>
/// and <see cref="EncodeBinary(byte[], Ecc)"/>.
/// </remarks>
/// <param name="segments">The segments to encode.</param>
/// <param name="ecl">The minimal or fixed error correction level to use .</param>
/// <param name="minVersion">The minimum version (size) of the QR code (between 1 and 40).</param>
/// <returns>The created QR code representing the segments.</returns>
/// <exception cref="ArgumentNullException"><paramref name="segments"/>, any list element, or <paramref name="ecl"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">1 ≤ minVersion ≤ maxVersion ≤ 40
/// or -1 ≤ mask ≤ 7 is violated.</exception>
/// <exception cref="DataTooLongException">The segments are too long to fit in the largest QR code size (version)
/// at the specified error correction level.</exception>
public static QrCode EncodeSegments(List<QrSegment> segments, Ecc ecl, int minVersion)
{
return EncodeSegments(segments, ecl, minVersion, MaxVersion, -1, true);
}
/// <summary>
/// Creates a QR code representing the specified segments with the specified encoding parameters.
/// <para>
/// The smallest possible QR code version (size) is used. The range of versions can be
/// restricted by the <paramref name="minVersion"/> and <paramref name="maxVersion"/> parameters.
/// </para>
/// <para>
/// The QR code mask is usually automatically chosen. It can be explicitly set with the <paramref name="mask"/>
/// parameter by using a value between 0 to 7 (inclusive). -1 is for automatic mode (which may be slow).
/// </para>
/// <para>
/// This function allows the user to create a custom sequence of segments that switches
/// between modes (such as alphanumeric and byte) to encode text in less space and gives full control over all
/// encoding paramters.
/// </para>
/// </summary>
/// <remarks>
/// This is a mid-level API; the high-level APIs are <see cref="EncodeText(string, Ecc)"/>
/// and <see cref="EncodeBinary(byte[], Ecc)"/>.
/// </remarks>
/// <param name="segments">The segments to encode.</param>
/// <param name="ecl">The minimal or fixed error correction level to use .</param>
/// <param name="minVersion">The minimum version (size) of the QR code (between 1 and 40).</param>
/// <param name="maxVersion">The maximum version (size) of the QR code (between 1 and 40).</param>
/// <returns>The created QR code representing the segments.</returns>
/// <exception cref="ArgumentNullException"><paramref name="segments"/>, any list element, or <paramref name="ecl"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">1 ≤ minVersion ≤ maxVersion ≤ 40
/// or -1 ≤ mask ≤ 7 is violated.</exception>
/// <exception cref="DataTooLongException">The segments are too long to fit in the largest QR code size (version)
/// at the specified error correction level.</exception>
public static QrCode EncodeSegments(List<QrSegment> segments, Ecc ecl, int minVersion, int maxVersion)
{
return EncodeSegments(segments, ecl, minVersion, maxVersion, -1, true);
}
/// <summary>
/// Creates a QR code representing the specified segments with the specified encoding parameters.
/// <para>
/// The smallest possible QR code version (size) is used. The range of versions can be
/// restricted by the <paramref name="minVersion"/> and <paramref name="maxVersion"/> parameters.
/// </para>
/// <para>
/// The QR code mask is usually automatically chosen. It can be explicitly set with the <paramref name="mask"/>
/// parameter by using a value between 0 to 7 (inclusive). -1 is for automatic mode (which may be slow).
/// </para>
/// <para>
/// This function allows the user to create a custom sequence of segments that switches
/// between modes (such as alphanumeric and byte) to encode text in less space and gives full control over all
/// encoding paramters.
/// </para>
/// </summary>
/// <remarks>
/// This is a mid-level API; the high-level APIs are <see cref="EncodeText(string, Ecc)"/>
/// and <see cref="EncodeBinary(byte[], Ecc)"/>.
/// </remarks>
/// <param name="segments">The segments to encode.</param>
/// <param name="ecl">The minimal or fixed error correction level to use .</param>
/// <param name="minVersion">The minimum version (size) of the QR code (between 1 and 40).</param>
/// <param name="maxVersion">The maximum version (size) of the QR code (between 1 and 40).</param>
/// <param name="mask">The mask number to use (between 0 and 7), or -1 for automatic mask selection.</param>
/// <returns>The created QR code representing the segments.</returns>
/// <exception cref="ArgumentNullException"><paramref name="segments"/>, any list element, or <paramref name="ecl"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">1 ≤ minVersion ≤ maxVersion ≤ 40
/// or -1 ≤ mask ≤ 7 is violated.</exception>
/// <exception cref="DataTooLongException">The segments are too long to fit in the largest QR code size (version)
/// at the specified error correction level.</exception>
public static QrCode EncodeSegments(List<QrSegment> segments, Ecc ecl, int minVersion, int maxVersion, int mask)
{
return EncodeSegments(segments, ecl, minVersion, maxVersion, mask, true);
}
/// <summary>
/// Creates a QR code representing the specified segments with the specified encoding parameters.
/// <para>
/// The smallest possible QR code version (size) is used. The range of versions can be
/// restricted by the <paramref name="minVersion"/> and <paramref name="maxVersion"/> parameters.
/// </para>
/// <para>
/// If <paramref name="boostEcl"/> is <c>true</c>, the resulting ECC level will be higher than the
/// one specified if it can be achieved without increasing the size (version).
/// </para>
/// <para>
/// The QR code mask is usually automatically chosen. It can be explicitly set with the <paramref name="mask"/>
/// parameter by using a value between 0 to 7 (inclusive). -1 is for automatic mode (which may be slow).
/// </para>
/// <para>
/// This function allows the user to create a custom sequence of segments that switches
/// between modes (such as alphanumeric and byte) to encode text in less space and gives full control over all
/// encoding paramters.
/// </para>
/// </summary>
/// <remarks>
/// This is a mid-level API; the high-level APIs are <see cref="EncodeText(string, Ecc)"/>
/// and <see cref="EncodeBinary(byte[], Ecc)"/>.
/// </remarks>
/// <param name="segments">The segments to encode.</param>
/// <param name="ecl">The minimal or fixed error correction level to use .</param>
/// <param name="minVersion">The minimum version (size) of the QR code (between 1 and 40).</param>
/// <param name="maxVersion">The maximum version (size) of the QR code (between 1 and 40).</param>
/// <param name="mask">The mask number to use (between 0 and 7), or -1 for automatic mask selection.</param>
/// <param name="boostEcl">If <c>true</c> the ECC level wil be increased if it can be achieved without increasing the size (version).</param>
/// <returns>The created QR code representing the segments.</returns>
/// <exception cref="ArgumentNullException"><paramref name="segments"/>, any list element, or <paramref name="ecl"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">1 ≤ minVersion ≤ maxVersion ≤ 40
/// or -1 ≤ mask ≤ 7 is violated.</exception>
/// <exception cref="DataTooLongException">The segments are too long to fit in the largest QR code size (version)
/// at the specified error correction level.</exception>
public static QrCode EncodeSegments(List<QrSegment> segments, Ecc ecl, int minVersion, int maxVersion, int mask, bool boostEcl)
{
Objects.RequireNonNull(segments);
Objects.RequireNonNull(ecl);
if (minVersion < MinVersion || minVersion > maxVersion)
{
throw new ArgumentOutOfRangeException(nameof(minVersion), "Invalid value");
}
if (maxVersion > MaxVersion)
{
throw new ArgumentOutOfRangeException(nameof(maxVersion), "Invalid value");
}
if (mask < -1 || mask > 7)
{
throw new ArgumentOutOfRangeException(nameof(mask), "Invalid value");
}
// Find the minimal version number to use
int version, dataUsedBits;
for (version = minVersion; ; version++)
{
int numDataBits = GetNumDataCodewords(version, ecl) * 8; // Number of data bits available
dataUsedBits = QrSegment.GetTotalBits(segments, version);
if (dataUsedBits != -1 && dataUsedBits <= numDataBits)
{
break; // This version number is found to be suitable
}
if (version >= maxVersion)
{ // All versions in the range could not fit the given data
string msg = "Segment too long";
if (dataUsedBits != -1)
{
msg = "Data length = {dataUsedBits} bits, Max capacity = {numDataBits} bits";
}
throw new DataTooLongException(msg);
}
}
Debug.Assert(dataUsedBits != -1);
// Increase the error correction level while the data still fits in the current version number
foreach (Ecc newEcl in Ecc.AllValues)
{ // From low to high
if (boostEcl && dataUsedBits <= GetNumDataCodewords(version, newEcl) * 8)
{
ecl = newEcl;
}
}
// Concatenate all segments to create the data bit string
BitArray ba = new BitArray(0);
foreach (QrSegment seg in segments)
{
BitArrayExtensions.AppendBits(ba, seg.EncodingMode.ModeBits, 4);
BitArrayExtensions.AppendBits(ba, (uint)seg.NumChars, seg.EncodingMode.NumCharCountBits(version));
BitArrayExtensions.AppendData(ba, seg.GetData());
}
Debug.Assert(ba.Length == dataUsedBits);
// Add terminator and pad up to a byte if applicable
int dataCapacityBits = GetNumDataCodewords(version, ecl) * 8;
Debug.Assert(ba.Length <= dataCapacityBits);
BitArrayExtensions.AppendBits(ba, 0, Math.Min(4, dataCapacityBits - ba.Length));
BitArrayExtensions.AppendBits(ba, 0, (8 - ba.Length % 8) % 8);
Debug.Assert(ba.Length % 8 == 0);
// Pad with alternating bytes until data capacity is reached
for (uint padByte = 0xEC; ba.Length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
{
BitArrayExtensions.AppendBits(ba, padByte, 8);
}
// Pack bits into bytes in big endian
byte[] dataCodewords = new byte[ba.Length / 8];
for (int i = 0; i < ba.Length; i++)
{
if (ba.Get(i))
{
dataCodewords[i >> 3] |= (byte)(1 << (7 - (i & 7)));
}
}
// Create the QR code object
return new QrCode(version, ecl, dataCodewords, mask);
}
private static string nameof(object obj) {
return obj.GetType().Name;
}
#endregion
#region Public immutable properties
/// <summary>
/// The version (size) of this QR code (between 1 for the smallest and 40 for the biggest).
/// </summary>
/// <value>The QR code version (size).</value>
public int Version { get{return _Version;} private set{_Version = value;} }
private int _Version;
/// <summary>
/// The width and height of this QR code, in modules (pixels).
/// The size is a value between 21 and 177.
/// This is equal to version × 4 + 17.
/// </summary>
/// <value>The QR code size.</value>
public int Size { get{return _Size;} private set{_Size = value;} }
private int _Size;
/// <summary>
/// The error correction level used for this QR code.
/// </summary>
/// <value>The error correction level.</value>
public Ecc ErrorCorrectionLevel { get{return _ErrorCorrectionLevel;}
private set{_ErrorCorrectionLevel = value;} }
private Ecc _ErrorCorrectionLevel;
/// <summary>
/// The index of the mask pattern used fort this QR code (between 0 and 7).
/// <para>
/// Even if a QR code is created with automatic mask selection (<c>mask</c> = 1),
/// this property returns the effective mask used.
/// </para>
/// </summary>
/// <value>The mask pattern index.</value>
public int Mask { get{return _Mask;} private set{_Mask = value;} }
private int _Mask;
#endregion
#region Private grids of modules/pixels, with dimensions of size * size
// The modules of this QR code (false = white, true = black).
// Immutable after constructor finishes. Accessed through GetModule().
private readonly bool[] _modules;
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
private readonly bool[] _isFunction;
#endregion
#region Constructor (low level)
/// <summary>
/// Constructs a QR code with the specified version number,
/// error correction level, data codeword bytes, and mask number.
/// </summary>
/// <remarks>
/// This is a low-level API that most users should not use directly. A mid-level
/// API is the <see cref="EncodeSegments"/> function.
/// </remarks>
/// <param name="version">The version (size) to use (between 1 to 40).</param>
/// <param name="ecl">The error correction level to use.</param>
/// <param name="dataCodewords">The bytes representing segments to encode (without ECC).</param>
/// <exception cref="ArgumentNullException"><paramref name="ecl"/> or <paramref name="dataCodewords"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">The version or mask value is out of range,
/// or the data has an invalid length for the specified version and error correction level.</exception>
public QrCode(int version, Ecc ecl, byte[] dataCodewords)
{
int mask = -1;
// Check arguments and initialize fields
if (version < MinVersion || version > MaxVersion)
{
throw new ArgumentOutOfRangeException(nameof(version), "Version value out of range");
}
if (mask < -1 || mask > 7)
{
throw new ArgumentOutOfRangeException(nameof(mask), "Mask value out of range");
}
Version = version;
Size = version * 4 + 17;
Objects.RequireNonNull(ecl);
ErrorCorrectionLevel = ecl;
Objects.RequireNonNull(dataCodewords);
_modules = new bool[Size * Size]; // Initially all white
_isFunction = new bool[Size * Size];
// Compute ECC, draw modules, do masking
DrawFunctionPatterns();
byte[] allCodewords = AddEccAndInterleave(dataCodewords);
DrawCodewords(allCodewords);
Mask = HandleConstructorMasking(mask);
_isFunction = null;
}
/// <summary>
/// Constructs a QR code with the specified version number,
/// error correction level, data codeword bytes, and mask number.
/// </summary>
/// <remarks>
/// This is a low-level API that most users should not use directly. A mid-level
/// API is the <see cref="EncodeSegments"/> function.
/// </remarks>
/// <param name="version">The version (size) to use (between 1 to 40).</param>
/// <param name="ecl">The error correction level to use.</param>
/// <param name="dataCodewords">The bytes representing segments to encode (without ECC).</param>
/// <param name="mask">The mask pattern to use (either -1 for automatic selection, or a value from 0 to 7 for fixed choice).</param>
/// <exception cref="ArgumentNullException"><paramref name="ecl"/> or <paramref name="dataCodewords"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">The version or mask value is out of range,
/// or the data has an invalid length for the specified version and error correction level.</exception>
public QrCode(int version, Ecc ecl, byte[] dataCodewords, int mask)
{
// Check arguments and initialize fields
if (version < MinVersion || version > MaxVersion)
{
throw new ArgumentOutOfRangeException(nameof(version), "Version value out of range");
}
if (mask < -1 || mask > 7)
{
throw new ArgumentOutOfRangeException(nameof(mask), "Mask value out of range");
}
Version = version;
Size = version * 4 + 17;
Objects.RequireNonNull(ecl);
ErrorCorrectionLevel = ecl;
Objects.RequireNonNull(dataCodewords);
_modules = new bool[Size * Size]; // Initially all white
_isFunction = new bool[Size * Size];
// Compute ECC, draw modules, do masking
DrawFunctionPatterns();
byte[] allCodewords = AddEccAndInterleave(dataCodewords);
DrawCodewords(allCodewords);
Mask = HandleConstructorMasking(mask);
_isFunction = null;
}
#endregion
#region Public methods
/// <summary>
/// Gets the color of the module (pixel) at the specified coordinates.
/// <para>
/// The top left corner has the coordinates (x=0, y=0). <i>x</i>-coordinates extend from left to right,
/// <i>y</i>-coordinates extend from top to bottom.
/// </para>
/// <para>
/// If coordinates outside the bounds of this QR code are specified, white (<c>false</c>) is returned.
/// </para>
/// </summary>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <returns>The color of the specified module: <c>true</c> for black modules and <c>false</c>
/// for white modules (or if the coordinates are outside the bounds).</returns>
public bool GetModule(int x, int y)
{
return 0 <= x && x < Size && 0 <= y && y < Size && _modules[y * Size + x];
}
/// <summary>
/// Creates a bitmap (raster image) of this QR code.
/// <para>
/// The <paramref name="scale"/> parameter specifies the scale of the image, which is
/// equivalent to the width and height of each QR code module. Additionally, the number
/// of modules to add as a border to all four sides can be specified.
/// </para>
/// <para>
/// For example, <c>ToBitmap(scale: 10, border: 4)</c> means to pad the QR code with 4 white
/// border modules on all four sides, and use 10×10 pixels to represent each module.
/// </para>
/// <para>
/// The resulting bitmap uses the pixel format <see cref="PixelFormat.Format24bppRgb"/> and
/// only contains black (0x000000) and white (0xFFFFFF) pixels.
/// </para>
/// </summary>
/// <param name="scale">The width and height, in pixels, of each module.</param>
/// <param name="border">The number of border modules to add to each of the four sides.</param>
/// <returns>The created bitmap representing this QR code.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="scale"/> is 0 or negative, <paramref name="border"/> is negative
/// or the resulting image is wider than 32,768 pixels.</exception>
public Bitmap ToBitmap(int scale, int border)
{
if (scale <= 0)
{
throw new ArgumentOutOfRangeException(nameof(scale), "Value out of range");
}
if (border < 0)
{
throw new ArgumentOutOfRangeException(nameof(border), "Value out of range");
}
int dim = (Size + border * 2) * scale;
if (dim > short.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(scale), "Scale or border too large");
}
Bitmap bitmap = new Bitmap(dim, dim, PixelFormat.Format24bppRgb);
// simple and inefficient
for (int y = 0; y < dim; y++)
{
for (int x = 0; x < dim; x++)
{
bool color = GetModule(x / scale - border, y / scale - border);
bitmap.SetPixel(x, y, color ? Color.Black : Color.White);
}
}
return bitmap;
}
/// <summary>
/// Creates an SVG image of this QR code.
/// <para>
/// The images uses Unix newlines (\n), regardless of the platform.
/// </para>
/// </summary>
/// <param name="border">The number of border modules to add on all four sides.</param>
/// <returns>The created SVG XML document of this QR code as a string.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="border"/> is negative.</exception>
public string ToSvgString(int border)
{
if (border < 0)
{
throw new ArgumentOutOfRangeException(nameof(border), "Border must be non-negative");
}
int dim = Size + border * 2;
StringBuilder sb = new StringBuilder()
.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
.Append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n")
.Append("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {dim} {dim}\" stroke=\"none\">\n")
.Append("\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n")
.Append("\t<path d=\"");
for (int y = 0; y < Size; y++)
{
for (int x = 0; x < Size; x++)
{
if (!GetModule(x, y))
{
continue;
}
if (x != 0 || y != 0)
{
sb.Append(" ");
}
sb.Append("M{x + border},{y + border}h1v1h-1z");
}
}
return sb
.Append("\" fill=\"#000000\"/>\n")
.Append("</svg>\n")
.ToString();
}
#endregion
#region Private helper methods for constructor: Drawing function modules
// Reads this object's version field, and draws and marks all function modules.
private void DrawFunctionPatterns()
{
// Draw horizontal and vertical timing patterns
for (int i = 0; i < Size; i++)
{
SetFunctionModule(6, i, i % 2 == 0);
SetFunctionModule(i, 6, i % 2 == 0);
}
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
DrawFinderPattern(3, 3);
DrawFinderPattern(Size - 4, 3);
DrawFinderPattern(3, Size - 4);
// Draw numerous alignment patterns
int[] alignPatPos = GetAlignmentPatternPositions();
int numAlign = alignPatPos.Length;
for (int i = 0; i < numAlign; i++)
{
for (int j = 0; j < numAlign; j++)
{
// Don't draw on the three finder corners
if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
{
DrawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
}
}
}
// Draw configuration data
DrawFormatBits(0); // Dummy mask value; overwritten later in the constructor
DrawVersion();
}
// Draws two copies of the format bits (with its own error correction code)
// based on the given mask and this object's error correction level field.
private void DrawFormatBits(uint mask)
{
// Calculate error correction code and pack bits
uint data = (ErrorCorrectionLevel.FormatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3
uint rem = data;
for (int i = 0; i < 10; i++)
{
rem = (rem << 1) ^ ((rem >> 9) * 0x537);
}
uint bits = ((data << 10) | rem) ^ 0x5412; // uint15
Debug.Assert(bits >> 15 == 0);
// Draw first copy
for (int i = 0; i <= 5; i++)
{
SetFunctionModule(8, i, GetBit(bits, i));
}
SetFunctionModule(8, 7, GetBit(bits, 6));
SetFunctionModule(8, 8, GetBit(bits, 7));
SetFunctionModule(7, 8, GetBit(bits, 8));
for (int i = 9; i < 15; i++)
{
SetFunctionModule(14 - i, 8, GetBit(bits, i));
}
// Draw second copy
for (int i = 0; i < 8; i++)
{
SetFunctionModule(Size - 1 - i, 8, GetBit(bits, i));
}
for (int i = 8; i < 15; i++)
{
SetFunctionModule(8, Size - 15 + i, GetBit(bits, i));
}
SetFunctionModule(8, Size - 8, true); // Always black
}
// Draws two copies of the version bits (with its own error correction code),
// based on this object's version field, iff 7 <= version <= 40.
private void DrawVersion()
{
if (Version < 7)
{
return;
}
// Calculate error correction code and pack bits
uint rem = (uint)Version; // version is uint6, in the range [7, 40]
for (int i = 0; i < 12; i++)
{
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
}
uint bits = ((uint)Version << 12) | rem; // uint18
Debug.Assert(bits >> 18 == 0);
// Draw two copies
for (int i = 0; i < 18; i++)
{
bool bit = GetBit(bits, i);
int a = Size - 11 + i % 3;
int b = i / 3;
SetFunctionModule(a, b, bit);
SetFunctionModule(b, a, bit);
}
}
// Draws a 9*9 finder pattern including the border separator,
// with the center module at (x, y). Modules can be out of bounds.
private void DrawFinderPattern(int x, int y)
{
for (int dy = -4; dy <= 4; dy++)
{
for (int dx = -4; dx <= 4; dx++)
{
int dist = Math.Max(Math.Abs(dx), Math.Abs(dy)); // Chebyshev/infinity norm
int xx = x + dx, yy = y + dy;
if (0 <= xx && xx < Size && 0 <= yy && yy < Size)
{
SetFunctionModule(xx, yy, dist != 2 && dist != 4);
}
}
}
}
// Draws a 5*5 alignment pattern, with the center module
// at (x, y). All modules must be in bounds.
private void DrawAlignmentPattern(int x, int y)
{
for (int dy = -2; dy <= 2; dy++)
{
for (int dx = -2; dx <= 2; dx++)
{
SetFunctionModule(x + dx, y + dy, Math.Max(Math.Abs(dx), Math.Abs(dy)) != 1);
}
}
}
// Sets the color of a module and marks it as a function module.
// Only used by the constructor. Coordinates must be in bounds.
private void SetFunctionModule(int x, int y, bool isBlack)
{
_modules[y * Size + x] = isBlack;
_isFunction[y * Size + x] = true;
}
#endregion
#region Private helper methods for constructor: Codewords and masking
// Returns a new byte string representing the given data with the appropriate error correction
// codewords appended to it, based on this object's version and error correction level.
private byte[] AddEccAndInterleave(byte[] data)
{
Objects.RequireNonNull(data);
if (data.Length != GetNumDataCodewords(Version, ErrorCorrectionLevel))
{
throw new ArgumentOutOfRangeException();
}
// Calculate parameter numbers
int numBlocks = NumErrorCorrectionBlocks[ErrorCorrectionLevel.Ordinal, Version];
int blockEccLen = EccCodewordsPerBlock[ErrorCorrectionLevel.Ordinal, Version];
int rawCodewords = GetNumRawDataModules(Version) / 8;
int numShortBlocks = numBlocks - rawCodewords % numBlocks;
int shortBlockLen = rawCodewords / numBlocks;
// Split data into blocks and append ECC to each block
byte[][] blocks = new byte[numBlocks][];
ReedSolomonGenerator rs = new ReedSolomonGenerator(blockEccLen);
for (int i = 0, k = 0; i < numBlocks; i++)
{
byte[] dat = CopyOfRange(data, k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
k += dat.Length;
byte[] block = CopyOf(dat, shortBlockLen + 1);
byte[] ecc = rs.GetRemainder(dat);
Array.Copy(ecc, 0, block, block.Length - blockEccLen, ecc.Length);
blocks[i] = block;
}
// Interleave (not concatenate) the bytes from every block into a single sequence
byte[] result = new byte[rawCodewords];
for (int i = 0, k = 0; i < blocks[0].Length; i++)
{
for (int j = 0; j < blocks.Length; j++)
{
// Skip the padding byte in short blocks
if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
{
result[k] = blocks[j][i];
k++;
}
}
}
return result;
}
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
// data area of this QR code. Function modules need to be marked off before this is called.
private void DrawCodewords(byte[] data)
{
Objects.RequireNonNull(data);
if (data.Length != GetNumRawDataModules(Version) / 8)
{
throw new ArgumentOutOfRangeException();
}
int i = 0; // Bit index into the data
// Do the funny zigzag scan
for (int right = Size - 1; right >= 1; right -= 2)
{
// Index of right column in each column pair
if (right == 6)
{
right = 5;
}
for (int vert = 0; vert < Size; vert++)
{
// Vertical counter
for (int j = 0; j < 2; j++)
{
int x = right - j; // Actual x coordinate
bool upward = ((right + 1) & 2) == 0;
int y = upward ? Size - 1 - vert : vert; // Actual y coordinate
if (_isFunction[y * Size + x] || i >= data.Length * 8)
{
continue;
}
_modules[y * Size + x] = GetBit(data[(uint)i >> 3], 7 - (i & 7));
i++;
// If this QR code has any remainder bits (0 to 7), they were assigned as
// 0/false/white by the constructor and are left unchanged by this method
}
}
}
Debug.Assert(i == data.Length * 8);
}
// XORs the codeword modules in this QR code with the given mask pattern.
// The function modules must be marked and the codeword bits must be drawn
// before masking. Due to the arithmetic of XOR, calling applyMask() with
// the same mask value a second time will undo the mask. A final well-formed
// QR code needs exactly one (not zero, two, etc.) mask applied.
private void ApplyMask(uint mask)
{
if (mask > 7)
{
throw new ArgumentOutOfRangeException(nameof(mask), "Mask value out of range");
}
int index = 0;
for (int y = 0; y < Size; y++)
{
for (int x = 0; x < Size; x++)
{
bool invert;
switch (mask)
{
case 0: invert = (x + y) % 2 == 0; break;
case 1: invert = y % 2 == 0; break;
case 2: invert = x % 3 == 0; break;
case 3: invert = (x + y) % 3 == 0; break;
case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
case 5: invert = x * y % 2 + x * y % 3 == 0; break;
case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
default: Debug.Assert(false); return;
}
_modules[index] ^= invert & !_isFunction[index];
index++;
}
}
}
// A messy helper function for the constructor. This QR code must be in an unmasked state when this
// method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed.
// This method applies and returns the actual mask chosen, from 0 to 7.
private int HandleConstructorMasking(int mask)
{
if (mask == -1)
{
// Automatically choose best mask
int minPenalty = int.MaxValue;
for (uint i = 0; i < 8; i++)
{
ApplyMask(i);
DrawFormatBits(i);
int penalty = GetPenaltyScore();
if (penalty < minPenalty)
{
mask = (int)i;
minPenalty = penalty;
}
ApplyMask(i); // Undoes the mask due to XOR
}
}
Debug.Assert(0 <= mask && mask <= 7);
ApplyMask((uint)mask); // Apply the final choice of mask
DrawFormatBits((uint)mask); // Overwrite old format bits
return mask; // The caller shall assign this value to the final-declared field
}
// Calculates and returns the penalty score based on state of this QR code's current modules.
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
private int GetPenaltyScore()
{
int result = 0;
RunHistory runHistory = new RunHistory();
// Adjacent modules in row having same color, and finder-like patterns
int index = 0;
for (int y = 0; y < Size; y++)
{
runHistory.Reset();
bool color = false;
int runX = 0;
for (int x = 0; x < Size; x++)
{
if (_modules[index] == color)
{
runX++;