//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// private Byte[,] EncodeQRCode ( ErrorCorrection ErrorCorrection ) { // initialization Initialization(ErrorCorrection); // encode data EncodeData(); // calculate error correction CalculateErrorCorrection(); // iterleave data and error correction codewords InterleaveBlocks(); // build base matrix BuildBaseMatrix(); // load base matrix with data and error correction codewords LoadMatrixWithData(); // data masking SelectBastMask(); // add format information (error code level and mask code) AddFormatInformation(); // output array return(ResultMatrix); }
private void HandleTransferForSingleWearehouse(int wearehouse, DataView dataView, int newItemId, int newUnitId, int newManufacturerId, decimal ConversionFactor, string Remark, DateTime convertedEthDate, User user, bool changeExpiryDate, DateTime?ExpiryDate, bool changeBatchNo, string batchNo, int activityId, Issue stvLog, Order order, PickList picklist) { int receiptTypeID = ReceiptType.CONSTANTS.ERROR_CORRECTION; ReceiveService receiveService = new ReceiveService(); Receipt receipt = receiveService.CreateFakeReceiptWithInvoicePO(order.OrderTypeID, activityId, GeneralInfo.Current.SupplierID, Remark, stvLog.IDPrinted, receiptTypeID, user.ID, BLL.Settings.IsVaccine ? ReceiptConfirmationStatus.Constants.GRV_PRINTED : ReceiptConfirmationStatus.Constants.GRNF_PRINTED, wearehouse); //Loop throw the Dataview and Create Detail Transaction foreach (DataRowView dataRowView in dataView) { int receivePalletID = Convert.ToInt32(dataRowView["receivePalletId"]); decimal pack = Convert.ToDecimal(dataRowView["PickedQty"]); decimal convertedPack = Convert.ToDecimal(pack * Convert.ToDecimal(ConversionFactor)); if (pack != 0) { CreateDetailTransactionsForErrorCorrection(order, picklist, stvLog, receivePalletID, receipt.ID, user, convertedEthDate, newItemId, newUnitId, newManufacturerId, pack, convertedPack, ReceiptConfirmationStatus.Constants.GRNF_PRINTED, changeExpiryDate, ExpiryDate, changeBatchNo, batchNo); } } ErrorCorrection.Log(stvLog, receipt, ConversionFactor); }
//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// internal Byte[,] EncodeQRCode ( String DataString, ErrorCorrection ErrorCorrection ) { // make sure data string is not empty if (String.IsNullOrEmpty(DataString)) { throw new ApplicationException("Input data string is null or empty"); } // split input data string to segments delimited by SegmentMarker SegDataString = DataString.Split(new Char[] { PdfQRCode.SegmentMarker }, StringSplitOptions.RemoveEmptyEntries); if (SegDataString == null || SegDataString.Length == 0) { throw new ApplicationException("Input data string is null or empty"); } // create encoding mode array SegEncodingMode = new EncodingMode[SegDataString.Length]; // create QR code boolean aray return(EncodeQRCode(ErrorCorrection)); }
/// <summary> /// Encode one string into QRCode boolean matrix /// </summary> /// <param name="ErrorCorrection">Error correction (L, M, Q, H)</param> /// <param name="StringDataSegments">string data segments</param> /// <returns>QR Code boolean matrix</returns> public bool[,] Encode ( ErrorCorrection ErrorCorrection, string[] StringDataSegments ) { // empty if (StringDataSegments == null) { return(Encode(ErrorCorrection, (byte[][])null)); } // create bytes arrays byte[][] TempDataSegArray = new byte[StringDataSegments.Length][]; // loop for all segments for (int SegIndex = 0; SegIndex < StringDataSegments.Length; SegIndex++) { // convert string to byte array TempDataSegArray[SegIndex] = StrToByteArray(StringDataSegments[SegIndex]); } // convert string to byte array return(Encode(ErrorCorrection, TempDataSegArray)); }
//////////////////////////////////////////////////////////////////// /// <summary> /// PDF QR Code constructor /// </summary> /// <param name="Document">Parent PDF document.</param> /// <param name="DataString">Data string to encode.</param> /// <param name="ErrorCorrection">Error correction code.</param> //////////////////////////////////////////////////////////////////// public PdfQRCode ( PdfDocument Document, String DataString, ErrorCorrection ErrorCorrection ) : base(Document, ObjectType.Stream, "/XObject") { // create resource code ResourceCode = Document.GenerateResourceNumber('X'); // create QR Code object QREncoder Encoder = new QREncoder(); QRCodeMatrix = Encoder.EncodeQRCode(DataString, ErrorCorrection); MatrixDimension = Encoder.MatrixDimension; // create stream length object ImageLengthObject = new PdfObject(Document, ObjectType.Other); Dictionary.AddIndirectReference("/Length", ImageLengthObject); // set default values ModuleSize = 4; QuietZone = 16; // exit return; }
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, IDictionary <EncodeHintType, object> hints) { if (String.IsNullOrEmpty(contents)) { throw new ArgumentException("Found empty contents", contents); } if (format != BarcodeFormat.DATA_MATRIX) { throw new ArgumentException("Can only encode DATA_MATRIX, but got " + format); } if (width < 0 || height < 0) { throw new ArgumentException("Requested dimensions are too small: " + width + 'x' + height); } // Try to get force shape & min / max size SymbolShapeHint shape = SymbolShapeHint.FORCE_NONE; Dimension minSize = null; Dimension maxSize = null; if (hints != null) { var requestedShape = hints.ContainsKey(EncodeHintType.DATA_MATRIX_SHAPE) ? (SymbolShapeHint?)hints[EncodeHintType.DATA_MATRIX_SHAPE] : null; if (requestedShape != null) { shape = requestedShape.Value; } var requestedMinSize = hints.ContainsKey(EncodeHintType.MIN_SIZE) ? (Dimension)hints[EncodeHintType.MIN_SIZE] : null; if (requestedMinSize != null) { minSize = requestedMinSize; } var requestedMaxSize = hints.ContainsKey(EncodeHintType.MAX_SIZE) ? (Dimension)hints[EncodeHintType.MAX_SIZE] : null; if (requestedMaxSize != null) { maxSize = requestedMaxSize; } } //1. step: Data encodation String encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize); SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.Length, shape, minSize, maxSize, true); //2. step: ECC generation String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo); //3. step: Module placement in Matrix var placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight()); placement.place(); //4. step: low-level encoding return(encodeLowLevel(placement, symbolInfo)); }
//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// private void EncodeQRCode ( ErrorCorrection ErrorCorrection, Int32 QuietZone ) { // test input if (SegDataString == null || SegDataString.Length == 0) { throw new ApplicationException("Input data strings are null or empty"); } // create encoding mode array SegEncodingMode = new EncodingMode[SegDataString.Length]; // initialization Initialization(ErrorCorrection); // encode data EncodeData(); // calculate error correction CalculateErrorCorrection(); // iterleave data and error correction codewords InterleaveBlocks(); // build base matrix BuildBaseMatrix(); // load base matrix with data and error correction codewords LoadMatrixWithData(); // data masking SelectBastMask(); // add format information (error code level and mask code) AddFormatInformation(); // output matrix size in pixels Int32 SidePix = MatrixDimension + 2 * QuietZone; OutputMatrix = new Boolean[SidePix, SidePix]; // convert result matrix to output matrix for (Int32 Row = 0; Row < MatrixDimension; Row++) { for (Int32 Col = 0; Col < MatrixDimension; Col++) { if ((ResultMatrix[Row, Col] & 1) != 0) { OutputMatrix[QuietZone + Row, QuietZone + Col] = true; } } } // output array return; }
public void CalculateEccOfData_ShouldReturnCorrectEccForGivenData(byte[] data, byte[] expectedEcc) { // Act var ecc = ErrorCorrection.CalculateEcc(data, (byte)expectedEcc.Length); // Assert ecc.Should().BeEquivalentTo(expectedEcc); }
/// <summary> /// Encode one data segment into QRCode boolean matrix /// </summary> /// <param name="ErrorCorrection">Error correction (L, M, Q, H)</param> /// <param name="SingleDataSeg">Data segment byte array</param> /// <returns>QR Code boolean matrix</returns> public bool[,] Encode ( ErrorCorrection ErrorCorrection, byte[] SingleDataSeg ) { return(Encode(ErrorCorrection, new byte[][] { SingleDataSeg })); }
//////////////////////////////////////////////////////////////////// /// <summary> /// PDF QR Code constructor /// </summary> /// <param name="Document">Parent PDF document.</param> /// <param name="DataString">Data string to encode.</param> /// <param name="ErrorCorrection">Error correction code.</param> /// <param name="QuietZone">Quiet zone</param> //////////////////////////////////////////////////////////////////// public PdfQRCode ( PdfDocument Document, string DataString, ErrorCorrection ErrorCorrection, int QuietZone = 4 ) : base(Document) { // PdfQRCode constructor helper ConstructorHelper(DataString, null, ErrorCorrection, QuietZone); }
public void Compute_DifferentLevels_ShouldReturnCorrectEcc(byte level, int[] expectedEcc) { // Arrange int[] inputData = new[] { 16, 902, 1, 278, 827, 900, 295, 902, 2, 326, 823, 544, 900, 149, 900, 900 }; // Act int[] ecc = ErrorCorrection.Compute(level, inputData); // Assert ecc.Should().BeEquivalentTo(expectedEcc); }
//////////////////////////////////////////////////////////////////// /// <summary> /// PDF QR Code constructor /// </summary> /// <param name="Document">Parent PDF document.</param> /// <param name="SegDataString">Data string array to encode.</param> /// <param name="ErrorCorrection">Error correction code.</param> /// <param name="QuietZone">Quiet zone</param> /// <remarks> /// The program will calculate the best encoding mode for each segment. /// </remarks> //////////////////////////////////////////////////////////////////// public PdfQRCode ( PdfDocument Document, String[] SegDataString, ErrorCorrection ErrorCorrection, Int32 QuietZone = 4 ) : base(Document) { // PdfQRCode constructor helper ConstructorHelper(null, SegDataString, ErrorCorrection, QuietZone); return; }
public void CalculateEccOfData_ShouldReturnCorrectEccForGivenData(byte[] data, byte[] expectedResult) { // Arrange CodeSize size = CodeSizes.All.FirstOrDefault(x => x.DataCodewords >= data.Length) ?? throw new InvalidOperationException("Size not found"); // Act byte[] result = ErrorCorrection.CalculateEcc(data, size); // Assert result.Should().BeEquivalentTo(expectedResult); }
/// <summary> /// Create QR Code image /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event arguments</param> private void OnEncode(object sender, EventArgs e) { // get error correction code ErrorCorrection ErrorCorrection = (ErrorCorrection)ErrorCorrectionComboBox.SelectedIndex; // get data for QR Code string Data = DataTextBox.Text.Trim(); if (Data.Length == 0) { MessageBox.Show("Data must not be empty."); return; } // save state ProgramState.State.EncodeErrorCorrection = ErrorCorrection; ProgramState.State.EncodeData = Data; ProgramState.SaveState(); // disable buttons EnableButtons(false); try { // multi segment if (SeparatorCheckBox.Checked && Data.IndexOf('|') >= 0) { string[] Segments = Data.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); // encode data QRCodeEncoder.Encode(ErrorCorrection, Segments); } // single segment else { // encode data QRCodeEncoder.Encode(ErrorCorrection, Data); } // create bitmap QRCodeImage = QRCodeToBitmap.CreateBitmap(QRCodeEncoder, 4, 8); } catch (Exception Ex) { MessageBox.Show("Encoding exception.\r\n" + Ex.Message); } // enable buttons EnableButtons(true); // repaint panel Invalidate(); return; }
//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// internal void EncodeQRCode ( string[] SegDataString, ErrorCorrection ErrorCorrection, int QuietZone ) { // save data string array this.SegDataString = SegDataString; // create QR code boolean aray EncodeQRCode(ErrorCorrection, QuietZone); }
public void testRS() { //Sample from Annexe R in ISO/IEC 16022:2000(E) char[] cw = { (char)142, (char)164, (char)186 }; SymbolInfo symbolInfo = SymbolInfo.lookup(3); String s = ErrorCorrection.encodeECC200(String.Join("", cw), symbolInfo); Assert.AreEqual("142 164 186 114 25 5 88 102", HighLevelEncodeTestCase.visualize(s)); //"A" encoded (ASCII encoding + 2 padding characters) cw = new char[] { (char)66, (char)129, (char)70 }; s = ErrorCorrection.encodeECC200(String.Join("", cw), symbolInfo); Assert.AreEqual("66 129 70 138 234 82 82 95", HighLevelEncodeTestCase.visualize(s)); }
public override void WriteInitializationScript(System.IO.TextWriter writer) { if (ErrorCorrection != DefaultErrorCorrection) { Options["errorCorrection"] = ErrorCorrection.ToString(); } if (Encoding != DefaultEncoding) { Options["encoding"] = Encoding.ToString(); } if (!string.IsNullOrEmpty(Value)) { Options["value"] = Value; } if (RenderAs.HasValue) { Options["renderAs"] = RenderAs.ToString().ToLowerInvariant(); } if (!string.IsNullOrEmpty(Background)) { Options["background"] = Background; } if (!string.IsNullOrEmpty(Color)) { Options["color"] = Color; } if (this.Size.HasValue) { Options["size"] = Size; } if (this.Border.ShouldSerialize()) { Options["border"] = Border.ToJson(); } if (Padding.HasValue) { Options["padding"] = Padding; } writer.Write(Initializer.Initialize(Selector, "QRCode", Options)); base.WriteInitializationScript(writer); }
//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// internal Byte[,] EncodeQRCode( String[] SegDataString, ErrorCorrection ErrorCorrection ) { // save data string array this.SegDataString = SegDataString; if(SegDataString == null || SegDataString.Length == 0) throw new ApplicationException("Input data string is null or empty"); // create encoding mode array SegEncodingMode = new EncodingMode[SegDataString.Length]; // create QR code boolean aray return(EncodeQRCode(ErrorCorrection)); }
/// <summary> /// Encode one string into QRCode boolean matrix /// </summary> /// <param name="ErrorCorrection">Error correction (L, M, Q, H)</param> /// <param name="StringDataSegment">string data segment</param> /// <returns>QR Code boolean matrix</returns> public bool[,] Encode ( ErrorCorrection ErrorCorrection, string StringDataSegment ) { // empty if (string.IsNullOrEmpty(StringDataSegment)) { return(Encode(ErrorCorrection, (byte[][])null)); } // convert string to byte array return(Encode(ErrorCorrection, StrToByteArray(StringDataSegment))); }
//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// internal Byte[,] EncodeQRCode( String DataString, ErrorCorrection ErrorCorrection ) { // make sure data string is not empty if(String.IsNullOrEmpty(DataString)) throw new ApplicationException("Input data string is null or empty"); // split input data string to segments delimited by SegmentMarker SegDataString = DataString.Split(new Char[] {PdfQRCode.SegmentMarker}, StringSplitOptions.RemoveEmptyEntries); if(SegDataString == null || SegDataString.Length == 0) throw new ApplicationException("Input data string is null or empty"); // create encoding mode array SegEncodingMode = new EncodingMode[SegDataString.Length]; // create QR code boolean aray return(EncodeQRCode(ErrorCorrection)); }
//////////////////////////////////////////////////////////////////// // Default constructor //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// internal void EncodeQRCode ( string DataString, ErrorCorrection ErrorCorrection, int QuietZone ) { // make sure data string is not empty if (string.IsNullOrEmpty(DataString)) { throw new ApplicationException("Input data string is null or empty"); } // split input data string to segments delimited by SegmentMarker SegDataString = DataString.Split(new[] { PdfQRCode.SegmentMarker }, StringSplitOptions.RemoveEmptyEntries); // create QR code boolean aray EncodeQRCode(ErrorCorrection, QuietZone); }
//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// internal Byte[,] EncodeQRCode ( String[] SegDataString, ErrorCorrection ErrorCorrection ) { // save data string array this.SegDataString = SegDataString; if (SegDataString == null || SegDataString.Length == 0) { throw new ApplicationException("Input data string is null or empty"); } // create encoding mode array SegEncodingMode = new EncodingMode[SegDataString.Length]; // create QR code boolean aray return(EncodeQRCode(ErrorCorrection)); }
//////////////////////////////////////////////////////////////////// // Write object to PDF file //////////////////////////////////////////////////////////////////// internal void ConstructorHelper ( string DataString, string[] SegDataString, ErrorCorrection ErrorCorrection, int QuietZone = 4 ) { // create QR Code object var Encoder = new QREncoder(); if (DataString != null) { Encoder.EncodeQRCode(DataString, ErrorCorrection, QuietZone); } else { Encoder.EncodeQRCode(SegDataString, ErrorCorrection, QuietZone); } // output matrix // NOTE: Black=true, White=flase BWImage = Encoder.OutputMatrix; // image width and height in pixels MatrixDimension = Encoder.MatrixDimension; WidthPix = MatrixDimension + 2 * QuietZone; HeightPix = WidthPix; // image control for QR code ImageControl = new PdfImageControl { ReverseBW = true, SaveAs = SaveImageAs.BWImage }; // write stream object WriteObjectToPdfFile(); }
private XtraReport ReturnErrorCorrectionReport(int unitIdTo, int manufacturerIdTo, DataView dataView, decimal conversionFactor, int IDPRinted, bool changeExpiryDate = false, DateTime?expiryDate = null, bool changeBatchNo = false, string batchNo = null) { Item item = new Item(); item.LoadByPrimaryKey(ItemIDTo); ItemUnit itemUnit = new ItemUnit(); itemUnit.LoadByPrimaryKey(unitIdTo); Manufacturer manufacturer = new Manufacturer(); manufacturer.LoadByPrimaryKey(manufacturerIdTo); Item itemFrom = new Item(); itemFrom.LoadByPrimaryKey(ItemID); ItemUnit ItemUnitFrom = new ItemUnit(); ItemUnitFrom.LoadByPrimaryKey(Convert.ToInt32(lkUnit.EditValue)); Manufacturer manufacturerFrom = new Manufacturer(); manufacturerFrom.LoadByPrimaryKey(Convert.ToInt32(lkManufacturer.EditValue)); dataView.RowFilter = "pickedQty > 0"; foreach (DataRowView dataRowView in dataView) { decimal pack = Convert.ToDecimal(dataRowView["PickedQty"]); dataRowView["ChangedQty"] = Convert.ToDecimal(pack * Convert.ToDecimal(conversionFactor)); } XtraReport xtraReport = new ErrorCorrection(IDPRinted, item.StockCode, item.FullItemName, itemUnit.Text, manufacturer.Name, item.StockCode, itemFrom.FullItemName, ItemUnitFrom.Text, manufacturerFrom.Name, changeExpiryDate, expiryDate, changeBatchNo, batchNo); xtraReport.DataSource = dataView; return(xtraReport); }
//////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////// public PdfQRCode ( PdfDocument Document, String DataString, ErrorCorrection ErrorCorrection ) : base(Document, true, "/XObject") { // create resource code ResourceCode = Document.GenerateResourceNumber('X'); // create QR Code object QREncoder Encoder = new QREncoder(); QRCodeMatrix = Encoder.EncodeQRCode(DataString, ErrorCorrection); MatrixDimension = Encoder.MatrixDimension; // create stream length object ImageLengthObject = new PdfObject(Document, false); AddToDictionary("/Length", ImageLengthObject.ObjectNumber.ToString() + " 0 R"); // exit return; }
//////////////////////////////////////////////////////////////////// // Initialization //////////////////////////////////////////////////////////////////// private void Initialization( ErrorCorrection ErrorCorrection ) { // save arguments this.ErrorCorrection = ErrorCorrection; // save error correction if(ErrorCorrection != ErrorCorrection.L && ErrorCorrection != ErrorCorrection.M && ErrorCorrection != ErrorCorrection.Q && ErrorCorrection != ErrorCorrection.H) throw new ApplicationException("Invalid error correction mode. Must be L, M, Q or H."); // reset to tal encoded data bits EncodedDataBits = 0; // loop for all segments for(Int32 SegIndex = 0; SegIndex < SegDataString.Length; SegIndex++) { // input string length String DataStr = SegDataString[SegIndex]; Int32 DataLength = DataStr.Length; // find encoding mode EncodingMode EncodingMode = EncodingMode.Numeric; for(Int32 Index = 0; Index < DataLength; Index++) { Int32 Value = (Int32) DataStr[Index]; if(Value > 255) throw new ApplicationException("Input string characters must be 0 to 255."); Int32 Code = EncodingTable[Value]; if(Code < 10) continue; if(Code < 45) { EncodingMode = EncodingMode.AlphaNumeric; continue; } EncodingMode = EncodingMode.Byte; break; } // calculate required bit length Int32 DataBits = 4; switch(EncodingMode) { case EncodingMode.Numeric: DataBits += 10 * (DataLength / 3); if((DataLength % 3) == 1) DataBits += 4; else if((DataLength % 3) == 2) DataBits += 7; break; case EncodingMode.AlphaNumeric: DataBits += 11 * (DataLength / 2); if((DataLength & 1) != 0) DataBits += 6; break; case EncodingMode.Byte: DataBits += 8 * DataLength; break; } SegEncodingMode[SegIndex] = EncodingMode; EncodedDataBits += DataBits; } // version is not defined yet, find best version Int32 TotalDataLenBits = 0; for(Version = 1; Version <= 40; Version++) { // number of bits on each side of the QR code square MatrixDimension = MatrixDimensionArray[Version]; SetDataCodewordsLength(); TotalDataLenBits = 0; for(Int32 Seg = 0; Seg < SegEncodingMode.Length; Seg++) TotalDataLenBits += DataLengthBits(SegEncodingMode[Seg]); if(EncodedDataBits + TotalDataLenBits <= MaxDataBits) break; } if(Version > 40) throw new ApplicationException("Input data string is too long"); EncodedDataBits += TotalDataLenBits; return; }
//////////////////////////////////////////////////////////////////// // Encode input byte array into QRCode boolean matrix //////////////////////////////////////////////////////////////////// private Byte[,] EncodeQRCode( ErrorCorrection ErrorCorrection ) { // initialization Initialization(ErrorCorrection); // encode data EncodeData(); // calculate error correction CalculateErrorCorrection(); // iterleave data and error correction codewords InterleaveBlocks(); // build base matrix BuildBaseMatrix(); // load base matrix with data and error correction codewords LoadMatrixWithData(); // data masking SelectBastMask(); // add format information (error code level and mask code) AddFormatInformation(); // output array return(ResultMatrix); }
public static ZPLCommand BQ(int qrVersion, int magnificationFactor, ErrorCorrection errorCorrection, int maskValue) => new ZPLCommand("^BQ", 'N', qrVersion, magnificationFactor, (char)errorCorrection, maskValue);
/// <summary> /// Encode data segments array into QRCode boolean matrix /// </summary> /// <param name="ErrorCorrection">Error correction (L, M, Q, H)</param> /// <param name="DataSegArray">Data array of byte arrays</param> /// <returns>QR Code boolean matrix</returns> public bool[,] Encode ( ErrorCorrection ErrorCorrection, byte[][] DataSegArray ) { // reset result variables QRCodeMatrix = null; QRCodeVersion = 0; QRCodeDimension = 0; // test error correction if (ErrorCorrection != ErrorCorrection.L && ErrorCorrection != ErrorCorrection.M && ErrorCorrection != ErrorCorrection.Q && ErrorCorrection != ErrorCorrection.H) { throw new ApplicationException("Invalid error correction mode. Must be L, M, Q or H."); } // test data segments array if (DataSegArray == null || DataSegArray.Length == 0) { throw new ApplicationException("Input data segment argument is missing."); } // loop for all segments int Bytes = 0; for (int SegIndex = 0; SegIndex < DataSegArray.Length; SegIndex++) { // input string length byte[] DataSeg = DataSegArray[SegIndex]; if (DataSeg == null) { DataSegArray[SegIndex] = new byte[0]; } else { Bytes += DataSeg.Length; } } if (Bytes == 0) { throw new ApplicationException("There is nothing to encode."); } // save error correction this.ErrorCorrection = ErrorCorrection; // save data segments array this.DataSegArray = DataSegArray; // initialization Initialization(); // encode data EncodeData(); // calculate error correction CalculateErrorCorrection(); // iterleave data and error correction codewords InterleaveBlocks(); // build base matrix BuildBaseMatrix(); // load base matrix with data and error correction codewords LoadMatrixWithData(); // data masking SelectBastMask(); // add format information (error code level and mask code) AddFormatInformation(); // output matrix size in pixels QRCodeMatrix = new bool[QRCodeDimension, QRCodeDimension]; // convert result matrix to output matrix // Black=true, White=false for (int Row = 0; Row < QRCodeDimension; Row++) { for (int Col = 0; Col < QRCodeDimension; Col++) { if ((ResultMatrix[Row, Col] & 1) != 0) { QRCodeMatrix[Row, Col] = true; } } } // exit with result return(QRCodeMatrix); }
private void EncodeButton_Click(object sender, EventArgs e) { // get error correction code ErrorCorrection ErrorCorrection = (ErrorCorrection)ErrorCorrectionComboBox.SelectedIndex; // get data for QR Code StringBuilder b = new StringBuilder(); if (lsvThietBi.SelectedIndices.Count > 0) { b.AppendLine(this.label1.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[0].Text); b.AppendLine(this.label2.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[1].Text); b.AppendLine(this.label3.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[2].Text); b.AppendLine(this.label4.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[3].Text); b.AppendLine(this.label5.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[4].Text); b.AppendLine(this.label6.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[5].Text); b.AppendLine(this.label7.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[6].Text); b.AppendLine(this.label8.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[7].Text); b.AppendLine(this.label9.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[8].Text); b.AppendLine(this.label10.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[9].Text); b.AppendLine(this.label12.Text + ":" + lsvThietBi.SelectedItems[0].SubItems[10].Text); } else { MessageBox.Show("You don't choose data!"); return; } string Data = b.ToString(); // save state ProgramState.State.EncodeErrorCorrection = ErrorCorrection; ProgramState.State.EncodeData = Data; ProgramState.SaveState(); // disable buttons EnableButtons(false); try { // multi segment if (SeparatorCheckBox.Checked && Data.IndexOf('|') >= 0) { string[] Segments = Data.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); // encode data QRCodeEncoder.Encode(ErrorCorrection, Segments); } // single segment else { // encode data QRCodeEncoder.Encode(ErrorCorrection, Data); } // create bitmap QRCodeImage = QRCodeToBitmap.CreateBitmap(QRCodeEncoder, 4, 8); } catch (Exception Ex) { MessageBox.Show("Encoding exception.\r\n" + Ex.Message); } // enable buttons EnableButtons(true); // repaint panel Invalidate(); return; }
/// <summary> /// Create a QR symbol that represents the supplied `data' with the indicated minimum level of error correction. /// </summary> /// <param name="data"></param> /// <param name="type"></param> /// <param name="errorCorrection"></param> public QRCode(string data, ErrorCorrection minimumErrorCorrection) : this(data, minimumErrorCorrection, false) { }
//////////////////////////////////////////////////////////////////// /// <summary> /// PDF QR Code constructor /// </summary> /// <param name="Document">Parent PDF document.</param> /// <param name="SegDataString">Data string array to encode.</param> /// <param name="ErrorCorrection">Error correction code.</param> /// <remarks> /// The program will calculate the best encoding mode for each segment. /// </remarks> //////////////////////////////////////////////////////////////////// public PdfQRCode( PdfDocument Document, String[] SegDataString, ErrorCorrection ErrorCorrection ) : base(Document, ObjectType.Stream, "/XObject") { // create resource code ResourceCode = Document.GenerateResourceNumber('X'); // create QR Code object QREncoder Encoder = new QREncoder(); QRCodeMatrix = Encoder.EncodeQRCode(SegDataString, ErrorCorrection); MatrixDimension = Encoder.MatrixDimension; // create stream length object ImageLengthObject = new PdfObject(Document, ObjectType.Other); Dictionary.AddIndirectReference("/Length", ImageLengthObject); // exit return; }
/// <summary> /// encodes the content to a BitMatrix /// </summary> /// <param name="contents"></param> /// <param name="format"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="hints"></param> /// <returns></returns> public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, IDictionary <EncodeHintType, object> hints) { if (String.IsNullOrEmpty(contents)) { throw new ArgumentException("Found empty contents", contents); } if (format != BarcodeFormat.DATA_MATRIX) { throw new ArgumentException("Can only encode DATA_MATRIX, but got " + format); } if (width < 0 || height < 0) { throw new ArgumentException("Requested dimensions can't be negative: " + width + 'x' + height); } // Try to get force shape & min / max size var shape = SymbolShapeHint.FORCE_NONE; var defaultEncodation = Encodation.ASCII; Dimension minSize = null; Dimension maxSize = null; if (hints != null) { if (hints.ContainsKey(EncodeHintType.DATA_MATRIX_SHAPE)) { var requestedShape = hints[EncodeHintType.DATA_MATRIX_SHAPE]; if (requestedShape is SymbolShapeHint) { shape = (SymbolShapeHint)requestedShape; } else { if (Enum.IsDefined(typeof(SymbolShapeHint), requestedShape.ToString())) { shape = (SymbolShapeHint)Enum.Parse(typeof(SymbolShapeHint), requestedShape.ToString(), true); } } } var requestedMinSize = hints.ContainsKey(EncodeHintType.MIN_SIZE) ? hints[EncodeHintType.MIN_SIZE] as Dimension : null; if (requestedMinSize != null) { minSize = requestedMinSize; } var requestedMaxSize = hints.ContainsKey(EncodeHintType.MAX_SIZE) ? hints[EncodeHintType.MAX_SIZE] as Dimension : null; if (requestedMaxSize != null) { maxSize = requestedMaxSize; } if (hints.ContainsKey(EncodeHintType.DATA_MATRIX_DEFAULT_ENCODATION)) { var requestedDefaultEncodation = hints[EncodeHintType.DATA_MATRIX_DEFAULT_ENCODATION]; if (requestedDefaultEncodation != null) { defaultEncodation = Convert.ToInt32(requestedDefaultEncodation.ToString()); } } } //1. step: Data encodation String encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, defaultEncodation); SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.Length, shape, minSize, maxSize, true); //2. step: ECC generation String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo); //3. step: Module placement in Matrix var placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight()); placement.place(); //4. step: low-level encoding return(encodeLowLevel(placement, symbolInfo, width, height)); }
/// <summary> /// Choose suitable values for Type, Version, ErrorCorrection and Mode. /// </summary> /// <param name="data"></param> /// <returns></returns> private Mode ChooseParameters(string data, ErrorCorrection minimumErrorCorrection, bool allowMicroCodes) { // get list of error correction modes at least as good as the user-specified one var allowedErrorCorrectionModes = new ErrorCorrection[] { ErrorCorrection.None, ErrorCorrection.L, ErrorCorrection.M, ErrorCorrection.Q, ErrorCorrection.H, }.SkipWhile(e => e != minimumErrorCorrection).ToList(); // get the tightest-fit encoding mode Mode tightestMode; if (data.All(c => Char.IsDigit(c))) tightestMode = Mode.Numeric; else if (data.All(c => AlphaNumericTable.ContainsKey(c))) tightestMode = Mode.AlphaNumeric; else tightestMode = Mode.Byte; // get list of allowed encoding modes var allowedModes = new Mode[] { Mode.Numeric, Mode.AlphaNumeric, Mode.Byte }.SkipWhile(m => m != tightestMode).ToList(); // get list of possible types List<Tuple<SymbolType, byte>> possibleTypes = allowMicroCodes ? Enumerable.Concat( Enumerable.Range(1, 4).Select(i => Tuple.Create(SymbolType.Micro, (byte)i)), Enumerable.Range(1, 40).Select(i => Tuple.Create(SymbolType.Normal, (byte)i))).ToList() : Enumerable.Range(1, 40).Select(i => Tuple.Create(SymbolType.Normal, (byte)i)).ToList(); // for each type in ascending order of size foreach (var p in possibleTypes) { // for each error correction level from most to least foreach (var e in allowedErrorCorrectionModes.Intersect(GetAvailableErrorCorrectionLevels(p.Item1, p.Item2)).Reverse()) { // lookup the data capacity var capacityEntry = DataCapacityTable.First(f => f.Item1 == p.Item1 && f.Item2 == p.Item2 && f.Item3 == e).Item4; // for each encoding mode from tightest to loosest foreach (var m in allowedModes.Intersect(GetAvailableModes(p.Item1, p.Item2))) { int capacity = 0; switch (m) { case Mode.Numeric: capacity = capacityEntry.Item2; break; case Mode.AlphaNumeric: capacity = capacityEntry.Item3; break; case Mode.Byte: capacity = capacityEntry.Item4; break; default: capacity = 0; break; } // if there is enough room, we've found our solution if (capacity >= data.Length) { Type = p.Item1; Version = p.Item2; ErrorCorrection = e; return m; } } } } throw new InvalidOperationException("no suitable parameters found"); }
/// <summary> /// Create a QR symbol that represents the supplied `data' with the indicated minimum level of error correction. /// </summary> public QRCode(string data, ErrorCorrection minimumErrorCorrection, bool allowMicroCodes) { var mode = ChooseParameters(data, minimumErrorCorrection, allowMicroCodes); var codeWords = CreateCodeWords(data, mode); var bits = AddErrorCorrection(codeWords); Reserve(); Fill(bits); var mask = Mask(); AddFormatInformation(mask); AddVersionInformation(); }
/// <summary> /// Initializes a new instance of the <see cref="Decoder"/> class. /// </summary> public Decoder() { errorCorrection = new ErrorCorrection(); }
private void OnEncode(object sender, EventArgs e) { // get error correction code ErrorCorrection ErrorCorrection = (ErrorCorrection)ErrorCorrectionComboBox.SelectedIndex; // get module size string ModuleStr = ModuleSizeTextBox.Text.Trim(); if (!int.TryParse(ModuleStr, out int ModuleSize) || ModuleSize < 1 || ModuleSize > 100) { MessageBox.Show("Module size error."); return; } // get quiet zone string QuietStr = QuietZoneTextBox.Text.Trim(); if (!int.TryParse(QuietStr, out int QuietZone) || QuietZone < 1 || QuietZone > 100) { MessageBox.Show("Quiet zone error."); return; } // get data for QR Code string Data = DataTextBox.Text.Trim(); if (Data.Length == 0) { MessageBox.Show("Data must not be empty."); return; } // disable buttons EnableButtons(false); try { QRCodeEncoder.ErrorCorrection = ErrorCorrection; QRCodeEncoder.ModuleSize = ModuleSize; QRCodeEncoder.QuietZone = QuietZone; // multi segment if (SeparatorCheckBox.Checked && Data.IndexOf('|') >= 0) { string[] Segments = Data.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); // encode data QRCodeEncoder.Encode(Segments); } // single segment else { // encode data QRCodeEncoder.Encode(Data); } // create bitmap QRCodeImage = QRCodeEncoder.CreateQRCodeBitmap(); } catch (Exception Ex) { MessageBox.Show("Encoding exception.\r\n" + Ex.Message); } // enable buttons EnableButtons(true); // repaint panel Invalidate(); return; }
//////////////////////////////////////////////////////////////////// // Initialization //////////////////////////////////////////////////////////////////// private void Initialization ( ErrorCorrection ErrorCorrection ) { // save arguments this.ErrorCorrection = ErrorCorrection; // save error correction if (ErrorCorrection != ErrorCorrection.L && ErrorCorrection != ErrorCorrection.M && ErrorCorrection != ErrorCorrection.Q && ErrorCorrection != ErrorCorrection.H) { throw new ApplicationException("Invalid error correction mode. Must be L, M, Q or H."); } // reset to tal encoded data bits EncodedDataBits = 0; // loop for all segments for (Int32 SegIndex = 0; SegIndex < SegDataString.Length; SegIndex++) { // input string length String DataStr = SegDataString[SegIndex]; Int32 DataLength = DataStr.Length; // find encoding mode EncodingMode EncodingMode = EncodingMode.Numeric; for (Int32 Index = 0; Index < DataLength; Index++) { Int32 Value = (Int32)DataStr[Index]; if (Value > 255) { throw new ApplicationException("Input string characters must be 0 to 255."); } Int32 Code = EncodingTable[Value]; if (Code < 10) { continue; } if (Code < 45) { EncodingMode = EncodingMode.AlphaNumeric; continue; } EncodingMode = EncodingMode.Byte; break; } // calculate required bit length Int32 DataBits = 4; switch (EncodingMode) { case EncodingMode.Numeric: DataBits += 10 * (DataLength / 3); if ((DataLength % 3) == 1) { DataBits += 4; } else if ((DataLength % 3) == 2) { DataBits += 7; } break; case EncodingMode.AlphaNumeric: DataBits += 11 * (DataLength / 2); if ((DataLength & 1) != 0) { DataBits += 6; } break; case EncodingMode.Byte: DataBits += 8 * DataLength; break; } SegEncodingMode[SegIndex] = EncodingMode; EncodedDataBits += DataBits; } // version is not defined yet, find best version Int32 TotalDataLenBits = 0; for (Version = 1; Version <= 40; Version++) { // number of bits on each side of the QR code square MatrixDimension = MatrixDimensionArray[Version]; SetDataCodewordsLength(); TotalDataLenBits = 0; for (Int32 Seg = 0; Seg < SegEncodingMode.Length; Seg++) { TotalDataLenBits += DataLengthBits(SegEncodingMode[Seg]); } if (EncodedDataBits + TotalDataLenBits <= MaxDataBits) { break; } } if (Version > 40) { throw new ApplicationException("Input data string is too long"); } EncodedDataBits += TotalDataLenBits; return; }