Search in sources :

Example 41 with DecoderResult

use of com.google.zxing.common.DecoderResult in project ofbiz-framework by apache.

the class QRCodeServices method generateQRCodeImage.

/**
 * Streams QR Code to the result.
 */
public static Map<String, Object> generateQRCodeImage(DispatchContext ctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    String message = (String) context.get("message");
    Integer width = (Integer) context.get("width");
    Integer height = (Integer) context.get("height");
    String format = (String) context.get("format");
    String encoding = (String) context.get("encoding");
    Boolean verifyOutput = (Boolean) context.get("verifyOutput");
    String logoImage = (String) context.get("logoImage");
    Integer logoImageMaxWidth = (Integer) context.get("logoImageMaxWidth");
    Integer logoImageMaxHeight = (Integer) context.get("logoImageMaxHeight");
    if (UtilValidate.isEmpty(message)) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ParameterCannotEmpty", new Object[] { "message" }, locale));
    }
    if (width == null) {
        width = Integer.parseInt(QRCODE_DEFAULT_WIDTH);
    }
    if (width.intValue() < MIN_SIZE || width.intValue() > MAX_SIZE) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "SizeOutOfBorderError", new Object[] { "width", String.valueOf(width), String.valueOf(MIN_SIZE), String.valueOf(MAX_SIZE) }, locale));
    }
    if (height == null) {
        height = Integer.parseInt(QRCODE_DEFAULT_HEIGHT);
    }
    if (height.intValue() < MIN_SIZE || height.intValue() > MAX_SIZE) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "SizeOutOfBorderError", new Object[] { "height", String.valueOf(height), String.valueOf(MIN_SIZE), String.valueOf(MAX_SIZE) }, locale));
    }
    if (UtilValidate.isEmpty(format)) {
        format = QRCODE_DEFAULT_FORMAT;
    }
    if (!FORMATS_SUPPORTED.contains(format)) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorFormatNotSupported", new Object[] { format }, locale));
    }
    Map<EncodeHintType, Object> encodeHints = null;
    if (UtilValidate.isNotEmpty(encoding)) {
        encodeHints = new EnumMap<>(EncodeHintType.class);
        encodeHints.put(EncodeHintType.CHARACTER_SET, encoding);
    }
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, width, height, encodeHints);
        BufferedImage bufferedImage = toBufferedImage(bitMatrix, format);
        BufferedImage logoBufferedImage = null;
        if (UtilValidate.isNotEmpty(logoImage)) {
            Map<String, Object> logoImageResult;
            try {
                logoImageResult = ImageTransform.getBufferedImage(FileUtil.getFile(logoImage).getAbsolutePath(), locale);
                logoBufferedImage = (BufferedImage) logoImageResult.get("bufferedImage");
            } catch (IllegalArgumentException | IOException e) {
                Debug.logError(e, module);
            }
        }
        if (UtilValidate.isEmpty(logoBufferedImage)) {
            logoBufferedImage = defaultLogoImage;
        }
        BufferedImage newBufferedImage = null;
        if (UtilValidate.isNotEmpty(logoBufferedImage)) {
            if (UtilValidate.isNotEmpty(logoImageMaxWidth) && UtilValidate.isNotEmpty(logoImageMaxHeight) && (logoBufferedImage.getWidth() > logoImageMaxWidth.intValue() || logoBufferedImage.getHeight() > logoImageMaxHeight.intValue())) {
                Map<String, String> typeMap = new HashMap<>();
                typeMap.put("width", logoImageMaxWidth.toString());
                typeMap.put("height", logoImageMaxHeight.toString());
                Map<String, Map<String, String>> dimensionMap = new HashMap<>();
                dimensionMap.put("QRCode", typeMap);
                Map<String, Object> logoImageResult = ImageTransform.scaleImage(logoBufferedImage, (double) logoBufferedImage.getWidth(), (double) logoBufferedImage.getHeight(), dimensionMap, "QRCode", locale);
                logoBufferedImage = (BufferedImage) logoImageResult.get("bufferedImage");
            }
            BitMatrix newBitMatrix = bitMatrix.clone();
            newBufferedImage = toBufferedImage(newBitMatrix, format);
            Graphics2D graphics = newBufferedImage.createGraphics();
            graphics.drawImage(logoBufferedImage, new AffineTransformOp(AffineTransform.getTranslateInstance(1, 1), null), (newBufferedImage.getWidth() - logoBufferedImage.getWidth()) / 2, (newBufferedImage.getHeight() - logoBufferedImage.getHeight()) / 2);
            graphics.dispose();
        }
        if (UtilValidate.isNotEmpty(verifyOutput) && verifyOutput.booleanValue()) {
            Decoder decoder = new Decoder();
            Map<DecodeHintType, Object> decodeHints = new EnumMap<>(DecodeHintType.class);
            decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            if (UtilValidate.isNotEmpty(encoding)) {
                decodeHints.put(DecodeHintType.CHARACTER_SET, encoding);
            }
            DetectorResult detectorResult = null;
            if (UtilValidate.isNotEmpty(newBufferedImage)) {
                BitMatrix newBitMatrix = createMatrixFromImage(newBufferedImage);
                DecoderResult result = null;
                try {
                    detectorResult = new Detector(newBitMatrix).detect(decodeHints);
                    result = decoder.decode(detectorResult.getBits(), decodeHints);
                } catch (ChecksumException | FormatException | NotFoundException e) {
                    Debug.logError(e, module);
                }
                if (UtilValidate.isNotEmpty(result) && !result.getText().equals(message)) {
                    detectorResult = new Detector(bitMatrix).detect(decodeHints);
                    result = decoder.decode(detectorResult.getBits(), decodeHints);
                    if (!result.getText().equals(message)) {
                        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "GeneratedTextNotMatchOriginal", new Object[] { result.getText(), message }, locale));
                    }
                } else {
                    bufferedImage = newBufferedImage;
                }
            } else {
                detectorResult = new Detector(bitMatrix).detect(decodeHints);
                DecoderResult result = decoder.decode(detectorResult.getBits(), decodeHints);
                if (!result.getText().equals(message)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "GeneratedTextNotMatchOriginal", new Object[] { result.getText(), message }, locale));
                }
            }
        } else if (UtilValidate.isNotEmpty(newBufferedImage)) {
            bufferedImage = newBufferedImage;
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.put("bufferedImage", bufferedImage);
        return result;
    } catch (WriterException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] { e.toString() }, locale));
    } catch (ChecksumException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] { e.toString() }, locale));
    } catch (FormatException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] { e.toString() }, locale));
    } catch (NotFoundException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage("QRCodeUiLabels", "ErrorVerifyQRCode", new Object[] { e.toString() }, locale));
    }
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) ChecksumException(com.google.zxing.ChecksumException) NotFoundException(com.google.zxing.NotFoundException) BitMatrix(com.google.zxing.common.BitMatrix) Decoder(com.google.zxing.qrcode.decoder.Decoder) BufferedImage(java.awt.image.BufferedImage) EncodeHintType(com.google.zxing.EncodeHintType) DecoderResult(com.google.zxing.common.DecoderResult) EnumMap(java.util.EnumMap) DecodeHintType(com.google.zxing.DecodeHintType) IOException(java.io.IOException) FormatException(com.google.zxing.FormatException) Graphics2D(java.awt.Graphics2D) AffineTransformOp(java.awt.image.AffineTransformOp) Detector(com.google.zxing.qrcode.detector.Detector) MultiFormatWriter(com.google.zxing.MultiFormatWriter) DetectorResult(com.google.zxing.common.DetectorResult) HashMap(java.util.HashMap) Map(java.util.Map) EnumMap(java.util.EnumMap) WriterException(com.google.zxing.WriterException)

Example 42 with DecoderResult

use of com.google.zxing.common.DecoderResult in project incubator-weex by apache.

the class DecodedBitStreamParser method decode.

static DecoderResult decode(byte[] bytes, int mode) {
    StringBuilder result = new StringBuilder(144);
    switch(mode) {
        case 2:
        case 3:
            String postcode;
            if (mode == 2) {
                int pc = getPostCode2(bytes);
                NumberFormat df = new DecimalFormat("0000000000".substring(0, getPostCode2Length(bytes)));
                postcode = df.format(pc);
            } else {
                postcode = getPostCode3(bytes);
            }
            String country = THREE_DIGITS.format(getCountry(bytes));
            String service = THREE_DIGITS.format(getServiceClass(bytes));
            result.append(getMessage(bytes, 10, 84));
            if (result.toString().startsWith("[)>" + RS + "01" + GS)) {
                result.insert(9, postcode + GS + country + GS + service + GS);
            } else {
                result.insert(0, postcode + GS + country + GS + service + GS);
            }
            break;
        case 4:
            result.append(getMessage(bytes, 1, 93));
            break;
        case 5:
            result.append(getMessage(bytes, 1, 77));
            break;
    }
    return new DecoderResult(bytes, result.toString(), null, String.valueOf(mode));
}
Also used : DecimalFormat(java.text.DecimalFormat) DecoderResult(com.google.zxing.common.DecoderResult) NumberFormat(java.text.NumberFormat)

Example 43 with DecoderResult

use of com.google.zxing.common.DecoderResult in project incubator-weex by apache.

the class AztecReader method decode.

@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType, ?> hints) throws NotFoundException, FormatException {
    NotFoundException notFoundException = null;
    FormatException formatException = null;
    Detector detector = new Detector(image.getBlackMatrix());
    ResultPoint[] points = null;
    DecoderResult decoderResult = null;
    try {
        AztecDetectorResult detectorResult = detector.detect(false);
        points = detectorResult.getPoints();
        decoderResult = new Decoder().decode(detectorResult);
    } catch (NotFoundException e) {
        notFoundException = e;
    } catch (FormatException e) {
        formatException = e;
    }
    if (decoderResult == null) {
        try {
            AztecDetectorResult detectorResult = detector.detect(true);
            points = detectorResult.getPoints();
            decoderResult = new Decoder().decode(detectorResult);
        } catch (NotFoundException | FormatException e) {
            if (notFoundException != null) {
                throw notFoundException;
            }
            if (formatException != null) {
                throw formatException;
            }
            throw e;
        }
    }
    if (hints != null) {
        ResultPointCallback rpcb = (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
        if (rpcb != null) {
            for (ResultPoint point : points) {
                rpcb.foundPossibleResultPoint(point);
            }
        }
    }
    Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.AZTEC);
    List<byte[]> byteSegments = decoderResult.getByteSegments();
    if (byteSegments != null) {
        result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
    }
    String ecLevel = decoderResult.getECLevel();
    if (ecLevel != null) {
        result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
    }
    return result;
}
Also used : ResultPointCallback(com.google.zxing.ResultPointCallback) ResultPoint(com.google.zxing.ResultPoint) NotFoundException(com.google.zxing.NotFoundException) Decoder(com.google.zxing.aztec.decoder.Decoder) FormatException(com.google.zxing.FormatException) Result(com.google.zxing.Result) DecoderResult(com.google.zxing.common.DecoderResult) Detector(com.google.zxing.aztec.detector.Detector) DecoderResult(com.google.zxing.common.DecoderResult)

Example 44 with DecoderResult

use of com.google.zxing.common.DecoderResult in project incubator-weex by apache.

the class Decoder method decode.

public DecoderResult decode(AztecDetectorResult detectorResult) throws FormatException {
    ddata = detectorResult;
    BitMatrix matrix = detectorResult.getBits();
    boolean[] rawbits = extractBits(matrix);
    boolean[] correctedBits = correctBits(rawbits);
    String result = getEncodedData(correctedBits);
    return new DecoderResult(null, result, null, null);
}
Also used : DecoderResult(com.google.zxing.common.DecoderResult) BitMatrix(com.google.zxing.common.BitMatrix)

Example 45 with DecoderResult

use of com.google.zxing.common.DecoderResult in project incubator-weex by apache.

the class Decoder method decode.

/**
 * <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
 *
 * @param bits booleans representing white/black QR Code modules
 * @param hints decoding hints that should be used to influence decoding
 * @return text and bytes encoded within the QR Code
 * @throws FormatException if the QR Code cannot be decoded
 * @throws ChecksumException if error correction fails
 */
public DecoderResult decode(BitMatrix bits, Map<DecodeHintType, ?> hints) throws FormatException, ChecksumException {
    // Construct a parser and read version, error-correction level
    BitMatrixParser parser = new BitMatrixParser(bits);
    FormatException fe = null;
    ChecksumException ce = null;
    try {
        return decode(parser, hints);
    } catch (FormatException e) {
        fe = e;
    } catch (ChecksumException e) {
        ce = e;
    }
    try {
        // Revert the bit matrix
        parser.remask();
        // Will be attempting a mirrored reading of the version and format info.
        parser.setMirror(true);
        // Preemptively read the version.
        parser.readVersion();
        // Preemptively read the format information.
        parser.readFormatInformation();
        /*
       * Since we're here, this means we have successfully detected some kind
       * of version and format information when mirrored. This is a good sign,
       * that the QR code may be mirrored, and we should try once more with a
       * mirrored content.
       */
        // Prepare for a mirrored reading.
        parser.mirror();
        DecoderResult result = decode(parser, hints);
        // Success! Notify the caller that the code was mirrored.
        result.setOther(new QRCodeDecoderMetaData(true));
        return result;
    } catch (FormatException | ChecksumException e) {
        // Throw the exception from the original reading
        if (fe != null) {
            throw fe;
        }
        if (ce != null) {
            throw ce;
        }
        throw e;
    }
}
Also used : ChecksumException(com.google.zxing.ChecksumException) DecoderResult(com.google.zxing.common.DecoderResult) FormatException(com.google.zxing.FormatException)

Aggregations

DecoderResult (com.google.zxing.common.DecoderResult)57 ResultPoint (com.google.zxing.ResultPoint)27 Result (com.google.zxing.Result)24 BitMatrix (com.google.zxing.common.BitMatrix)21 ArrayList (java.util.ArrayList)16 DetectorResult (com.google.zxing.common.DetectorResult)13 FormatException (com.google.zxing.FormatException)9 BitSource (com.google.zxing.common.BitSource)8 CharacterSetECI (com.google.zxing.common.CharacterSetECI)8 QRCodeDecoderMetaData (com.google.zxing.qrcode.decoder.QRCodeDecoderMetaData)8 Decoder (com.google.zxing.aztec.decoder.Decoder)7 NotFoundException (com.google.zxing.NotFoundException)6 ChecksumException (com.google.zxing.ChecksumException)5 Detector (com.google.zxing.qrcode.detector.Detector)5 ReaderException (com.google.zxing.ReaderException)4 ResultPointCallback (com.google.zxing.ResultPointCallback)4 AztecDetectorResult (com.google.zxing.aztec.AztecDetectorResult)4 Detector (com.google.zxing.aztec.detector.Detector)4 Detector (com.google.zxing.datamatrix.detector.Detector)4 MultiDetector (com.google.zxing.multi.qrcode.detector.MultiDetector)4