Search in sources :

Example 21 with WriterException

use of com.google.zxing.WriterException in project CloudReader by youlookwhat.

the class QRCodeUtil method createQRImage.

/**
     * 生成二维码Bitmap
     *
     * @param content   内容
     * @param widthPix  图片宽度
     * @param heightPix 图片高度
     * @param logoBm    二维码中心的Logo图标(可以为null)
     * @param filePath  用于存储二维码图片的文件路径
     * @return 生成二维码及保存文件是否成功
     */
public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
    try {
        if (content == null || "".equals(content)) {
            return false;
        }
        //配置参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //容错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //设置空白边距的宽度
        //            hints.put(EncodeHintType.MARGIN, 2); //default is 4
        // 图像数据转换,使用了矩阵转换
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
        int[] pixels = new int[widthPix * heightPix];
        // 两个for循环是图片横列扫描的结果
        for (int y = 0; y < heightPix; y++) {
            for (int x = 0; x < widthPix; x++) {
                if (bitMatrix.get(x, y)) {
                    pixels[y * widthPix + x] = 0xff000000;
                } else {
                    pixels[y * widthPix + x] = 0xffffffff;
                }
            }
        }
        // 生成二维码图片的格式,使用ARGB_8888
        Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
        if (logoBm != null) {
            bitmap = addLogo(bitmap, logoBm);
        }
        //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
        return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
    } catch (WriterException | IOException e) {
        e.printStackTrace();
    }
    return false;
}
Also used : HashMap(java.util.HashMap) BitMatrix(com.google.zxing.common.BitMatrix) IOException(java.io.IOException) QRCodeWriter(com.google.zxing.qrcode.QRCodeWriter) Bitmap(android.graphics.Bitmap) EncodeHintType(com.google.zxing.EncodeHintType) FileOutputStream(java.io.FileOutputStream) WriterException(com.google.zxing.WriterException)

Example 22 with WriterException

use of com.google.zxing.WriterException in project zxing by zxing.

the class ChartServlet method doEncode.

private static void doEncode(ServletRequest request, HttpServletResponse response, boolean isPost) throws IOException {
    ChartServletRequestParameters parameters;
    try {
        parameters = doParseParameters(request, isPost);
    } catch (IllegalArgumentException | NullPointerException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
        return;
    }
    Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
    hints.put(EncodeHintType.MARGIN, parameters.getMargin());
    if (!StandardCharsets.ISO_8859_1.equals(parameters.getOutputEncoding())) {
        // Only set if not QR code default
        hints.put(EncodeHintType.CHARACTER_SET, parameters.getOutputEncoding().name());
    }
    hints.put(EncodeHintType.ERROR_CORRECTION, parameters.getEcLevel());
    BitMatrix matrix;
    try {
        matrix = new QRCodeWriter().encode(parameters.getText(), BarcodeFormat.QR_CODE, parameters.getWidth(), parameters.getHeight(), hints);
    } catch (WriterException we) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, we.toString());
        return;
    }
    ByteArrayOutputStream pngOut = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(matrix, "PNG", pngOut);
    byte[] pngData = pngOut.toByteArray();
    response.setContentType("image/png");
    response.setContentLength(pngData.length);
    response.setHeader("Cache-Control", "public");
    response.getOutputStream().write(pngData);
}
Also used : BitMatrix(com.google.zxing.common.BitMatrix) ByteArrayOutputStream(java.io.ByteArrayOutputStream) QRCodeWriter(com.google.zxing.qrcode.QRCodeWriter) EncodeHintType(com.google.zxing.EncodeHintType) EnumMap(java.util.EnumMap) WriterException(com.google.zxing.WriterException)

Example 23 with WriterException

use of com.google.zxing.WriterException in project zxing by zxing.

the class EncoderTestCase method testAppendBytes.

@Test
public void testAppendBytes() throws WriterException {
    // Should use appendNumericBytes.
    // 1 = 01 = 0001 in 4 bits.
    BitArray bits = new BitArray();
    Encoder.appendBytes("1", Mode.NUMERIC, bits, Encoder.DEFAULT_BYTE_MODE_ENCODING);
    assertEquals(" ...X", bits.toString());
    // Should use appendAlphanumericBytes.
    // A = 10 = 0xa = 001010 in 6 bits
    bits = new BitArray();
    Encoder.appendBytes("A", Mode.ALPHANUMERIC, bits, Encoder.DEFAULT_BYTE_MODE_ENCODING);
    assertEquals(" ..X.X.", bits.toString());
    // Lower letters such as 'a' cannot be encoded in MODE_ALPHANUMERIC.
    try {
        Encoder.appendBytes("a", Mode.ALPHANUMERIC, bits, Encoder.DEFAULT_BYTE_MODE_ENCODING);
    } catch (WriterException we) {
    // good
    }
    // Should use append8BitBytes.
    // 0x61, 0x62, 0x63
    bits = new BitArray();
    Encoder.appendBytes("abc", Mode.BYTE, bits, Encoder.DEFAULT_BYTE_MODE_ENCODING);
    assertEquals(" .XX....X .XX...X. .XX...XX", bits.toString());
    // Anything can be encoded in QRCode.MODE_8BIT_BYTE.
    Encoder.appendBytes("\0", Mode.BYTE, bits, Encoder.DEFAULT_BYTE_MODE_ENCODING);
    // Should use appendKanjiBytes.
    // 0x93, 0x5f
    bits = new BitArray();
    Encoder.appendBytes(shiftJISString(new byte[] { (byte) 0x93, 0x5f }), Mode.KANJI, bits, Encoder.DEFAULT_BYTE_MODE_ENCODING);
    assertEquals(" .XX.XX.. XXXXX", bits.toString());
}
Also used : BitArray(com.google.zxing.common.BitArray) WriterException(com.google.zxing.WriterException) Test(org.junit.Test)

Example 24 with WriterException

use of com.google.zxing.WriterException in project zxing by zxing.

the class EncoderTestCase method testAppendAlphanumericBytes.

@Test
public void testAppendAlphanumericBytes() throws WriterException {
    // A = 10 = 0xa = 001010 in 6 bits
    BitArray bits = new BitArray();
    Encoder.appendAlphanumericBytes("A", bits);
    assertEquals(" ..X.X.", bits.toString());
    // AB = 10 * 45 + 11 = 461 = 0x1cd = 00111001101 in 11 bits
    bits = new BitArray();
    Encoder.appendAlphanumericBytes("AB", bits);
    assertEquals(" ..XXX..X X.X", bits.toString());
    // ABC = "AB" + "C" = 00111001101 + 001100
    bits = new BitArray();
    Encoder.appendAlphanumericBytes("ABC", bits);
    assertEquals(" ..XXX..X X.X..XX. .", bits.toString());
    // Empty.
    bits = new BitArray();
    Encoder.appendAlphanumericBytes("", bits);
    assertEquals("", bits.toString());
    // Invalid data.
    try {
        Encoder.appendAlphanumericBytes("abc", new BitArray());
    } catch (WriterException we) {
    // good
    }
}
Also used : BitArray(com.google.zxing.common.BitArray) WriterException(com.google.zxing.WriterException) Test(org.junit.Test)

Example 25 with WriterException

use of com.google.zxing.WriterException in project zxing by zxing.

the class PDF417HighLevelEncoder method determineConsecutiveBinaryCount.

/**
   * Determines the number of consecutive characters that are encodable using binary compaction.
   *
   * @param msg      the message
   * @param startpos the start position within the message
   * @param encoding the charset used to convert the message to a byte array
   * @return the requested character count
   */
private static int determineConsecutiveBinaryCount(String msg, int startpos, Charset encoding) throws WriterException {
    CharsetEncoder encoder = encoding.newEncoder();
    int len = msg.length();
    int idx = startpos;
    while (idx < len) {
        char ch = msg.charAt(idx);
        int numericCount = 0;
        while (numericCount < 13 && isDigit(ch)) {
            numericCount++;
            //textCount++;
            int i = idx + numericCount;
            if (i >= len) {
                break;
            }
            ch = msg.charAt(i);
        }
        if (numericCount >= 13) {
            return idx - startpos;
        }
        ch = msg.charAt(idx);
        if (!encoder.canEncode(ch)) {
            throw new WriterException("Non-encodable character detected: " + ch + " (Unicode: " + (int) ch + ')');
        }
        idx++;
    }
    return idx - startpos;
}
Also used : CharsetEncoder(java.nio.charset.CharsetEncoder) WriterException(com.google.zxing.WriterException)

Aggregations

WriterException (com.google.zxing.WriterException)32 Bitmap (android.graphics.Bitmap)14 BitMatrix (com.google.zxing.common.BitMatrix)10 QRCodeWriter (com.google.zxing.qrcode.QRCodeWriter)10 IOException (java.io.IOException)8 Intent (android.content.Intent)7 EncodeHintType (com.google.zxing.EncodeHintType)7 BitArray (com.google.zxing.common.BitArray)7 FileOutputStream (java.io.FileOutputStream)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Hashtable (java.util.Hashtable)4 Point (android.graphics.Point)3 Uri (android.net.Uri)3 Bundle (android.os.Bundle)3 Display (android.view.Display)3 WindowManager (android.view.WindowManager)3 ImageView (android.widget.ImageView)3 TextView (android.widget.TextView)3 Result (com.google.zxing.Result)3 AddressBookParsedResult (com.google.zxing.client.result.AddressBookParsedResult)3