encode method

  1. @override
BitMatrix encode(
  1. String contents,
  2. BarcodeFormat format,
  3. int width,
  4. int height, [
  5. EncodeHint? hints,
])
override

@param contents The contents to encode in the barcode @param format The barcode format to generate @param width The preferred width in pixels @param height The preferred height in pixels @param hints Additional parameters to supply to the encoder @return BitMatrix representing encoded barcode image @throws WriterException if contents cannot be encoded legally in a format

Implementation

@override
BitMatrix encode(
  String contents,
  BarcodeFormat format,
  int width,
  int height, [
  EncodeHint? hints,
]) {
  if (contents.isEmpty) {
    throw ArgumentError('Found empty contents');
  }

  if (format != BarcodeFormat.dataMatrix) {
    throw ArgumentError('Can only encode DATA_MATRIX, but got $format');
  }

  if (width < 0 || height < 0) {
    throw ArgumentError(
      "Requested dimensions can't be negative: $width" 'x$height',
    );
  }

  // Try to get force shape & min / max size
  SymbolShapeHint shape = SymbolShapeHint.forceNone;
  Dimension? minSize;
  Dimension? maxSize;
  if (hints != null) {
    final requestedShape = hints.dataMatrixShape;
    if (requestedShape != null) {
      shape = requestedShape;
    }

    // ignore: deprecated_member_use_from_same_package
    final requestedMinSize = hints.minSize;
    if (requestedMinSize != null) {
      minSize = requestedMinSize;
    }

    // ignore: deprecated_member_use_from_same_package
    final requestedMaxSize = hints.maxSize;
    if (requestedMaxSize != null) {
      maxSize = requestedMaxSize;
    }
  }

  //1. step: Data encodation
  String encoded;

  final hasCompactionHint = hints?.dataMatrixCompact ?? false;
  if (hasCompactionHint) {
    final hasGS1FormatHint = hints?.gs1Format ?? false;

    Encoding? charset;

    if (hints?.characterSet != null) {
      charset = CharacterSetECI.getCharacterSetECIByName(
        hints!.characterSet!,
      )?.charset;
    }
    encoded = MinimalEncoder.encodeHighLevel(
      contents,
      charset,
      hasGS1FormatHint ? 0x1D : -1,
      shape,
    );
  } else {
    encoded = HighLevelEncoder.encodeHighLevel(
      contents,
      shape,
      minSize,
      maxSize,
    );
  }

  final symbolInfo = SymbolInfo.lookup(
    encoded.length,
    shape,
    minSize,
    maxSize,
    true,
  );

  //2. step: ECC generation
  final codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo!);

  //3. step: Module placement in Matrix
  final placement = DefaultPlacement(
    codewords,
    symbolInfo.symbolDataWidth,
    symbolInfo.symbolDataHeight,
  );
  placement.place();

  //4. step: low-level encoding
  return _encodeLowLevel(placement, symbolInfo, width, height);
}