Search in sources :

Example 26 with QRCodeWriter

use of com.google.zxing.qrcode.QRCodeWriter in project krypton-android by kryptco.

the class AdminQR method onGetTeamHomeData.

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onGetTeamHomeData(TeamService.GetTeamHomeDataResult d) {
    if (d.r.error != null) {
        Error.shortToast(getContext(), d.r.error);
        Transitions.beginFade(this).remove(this).commitAllowingStateLoss();
        return;
    }
    Sigchain.TeamHomeData teamHomeData = d.r.success;
    Sigchain.QRPayload qrPayload = new Sigchain.QRPayload(new Sigchain.AdminQRPayload(teamHomeData.teamPublicKey, teamHomeData.lastBlockHash, teamHomeData.name));
    try {
        BitMatrix qrData = new QRCodeWriter().encode(JSON.toJson(qrPayload), BarcodeFormat.DATA_MATRIX.QR_CODE, 500, 500);
        qr.setImageBitmap(new BarcodeEncoder().createBitmap(qrData));
    } catch (WriterException e) {
        e.printStackTrace();
        Error.shortToast(getContext(), "Error creating QRCode");
        Transitions.beginFade(this).remove(this).commitAllowingStateLoss();
        return;
    }
}
Also used : QRCodeWriter(com.google.zxing.qrcode.QRCodeWriter) Sigchain(co.krypt.krypton.team.Sigchain) BarcodeEncoder(com.journeyapps.barcodescanner.BarcodeEncoder) BitMatrix(com.google.zxing.common.BitMatrix) WriterException(com.google.zxing.WriterException) Subscribe(org.greenrobot.eventbus.Subscribe)

Example 27 with QRCodeWriter

use of com.google.zxing.qrcode.QRCodeWriter in project toshi-android-client by toshiapp.

the class ImageUtil method generateQrCodeBitmap.

private static Bitmap generateQrCodeBitmap(@NonNull final String value) throws WriterException {
    final QRCodeWriter writer = new QRCodeWriter();
    final int size = BaseApplication.get().getResources().getDimensionPixelSize(R.dimen.qr_code_size);
    final Map<EncodeHintType, Integer> map = new HashMap<>();
    map.put(EncodeHintType.MARGIN, 0);
    final BitMatrix bitMatrix = writer.encode(value, BarcodeFormat.QR_CODE, size, size, map);
    final int width = bitMatrix.getWidth();
    final int height = bitMatrix.getHeight();
    final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    final int contrastColour = ContextCompat.getColor(BaseApplication.get(), R.color.windowBackground);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : contrastColour);
        }
    }
    return bmp;
}
Also used : QRCodeWriter(com.google.zxing.qrcode.QRCodeWriter) Bitmap(android.graphics.Bitmap) EncodeHintType(com.google.zxing.EncodeHintType) HashMap(java.util.HashMap) BitMatrix(com.google.zxing.common.BitMatrix)

Example 28 with QRCodeWriter

use of com.google.zxing.qrcode.QRCodeWriter in project i2p.i2p by i2p.

the class QRServlet method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getCharacterEncoding() == null)
        request.setCharacterEncoding("UTF-8");
    String codeParam = request.getParameter(PARAM_IDENTICON_CODE_SHORT);
    boolean codeSpecified = codeParam != null && codeParam.length() > 0;
    if (!codeSpecified) {
        response.setStatus(403);
        return;
    }
    String sizeParam = request.getParameter(PARAM_IDENTICON_SIZE_SHORT);
    // very rougly, number of "modules" is about 4 * sqrt(chars)
    // (assuming 7 bit) default margin each side is 4
    // assuming level L
    // min modules is 21x21
    // shoot for 2 pixels per module
    int size = Math.max(50, (2 * 4) + (int) (2 * 5 * Math.sqrt(codeParam.length())));
    if (sizeParam != null) {
        try {
            size = Integer.parseInt(sizeParam);
            if (size < 40)
                size = 40;
            else if (size > 512)
                size = 512;
        } catch (NumberFormatException nfe) {
        }
    }
    String identiconETag = IdenticonUtil.getIdenticonETag(codeParam.hashCode(), size, version);
    String requestETag = request.getHeader("If-None-Match");
    if (requestETag != null && requestETag.equals(identiconETag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        byte[] imageBytes = null;
        // retrieve image bytes from either cache or renderer
        if (cache == null || (imageBytes = cache.get(identiconETag)) == null) {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            QRCodeWriter qrcw = new QRCodeWriter();
            BitMatrix matrix;
            try {
                matrix = qrcw.encode(codeParam, BarcodeFormat.QR_CODE, size, size);
            } catch (WriterException we) {
                throw new IOException("encode failed", we);
            }
            String text = request.getParameter(PARAM_IDENTICON_TEXT_SHORT);
            if (text != null) {
                BufferedImage bi = MatrixToImageWriter.toBufferedImage(matrix);
                Graphics2D g = bi.createGraphics();
                // anti-aliasing and hinting degrade text with 1bit input, so let's turn this off to improve quality
                // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                // g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                // g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                // g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
                // g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                // g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                Font font = DEFAULT_LARGE_FONT;
                g.setFont(font);
                // doesn't work
                Color color = Color.RED;
                g.setColor(color);
                int width = bi.getWidth();
                int height = bi.getHeight();
                double swidth = font.getStringBounds(text, 0, text.length(), g.getFontRenderContext()).getBounds().getWidth();
                int x = (width - (int) swidth) / 2;
                int y = height - 10;
                g.drawString(text, x, y);
                if (!ImageIO.write(bi, IDENTICON_IMAGE_FORMAT, byteOut))
                    throw new IOException("ImageIO.write() fail");
            } else {
                MatrixToImageWriter.writeToStream(matrix, IDENTICON_IMAGE_FORMAT, byteOut);
            }
            imageBytes = byteOut.toByteArray();
            if (cache != null)
                cache.add(identiconETag, imageBytes);
        } else {
            response.setStatus(403);
            return;
        }
        // set ETag and, if code was provided, Expires header
        response.setHeader("ETag", identiconETag);
        if (codeSpecified) {
            long expires = System.currentTimeMillis() + identiconExpiresInMillis;
            response.addDateHeader("Expires", expires);
        }
        // return image bytes to requester
        response.setContentType(IDENTICON_IMAGE_MIMETYPE);
        response.setHeader("X-Content-Type-Options", "nosniff");
        response.setHeader("Accept-Ranges", "none");
        response.setContentLength(imageBytes.length);
        response.getOutputStream().write(imageBytes);
    }
}
Also used : Color(java.awt.Color) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BitMatrix(com.google.zxing.common.BitMatrix) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) Font(java.awt.Font) Graphics2D(java.awt.Graphics2D) QRCodeWriter(com.google.zxing.qrcode.QRCodeWriter) WriterException(com.google.zxing.WriterException)

Example 29 with QRCodeWriter

use of com.google.zxing.qrcode.QRCodeWriter 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 30 with QRCodeWriter

use of com.google.zxing.qrcode.QRCodeWriter in project HL4A by HL4A.

the class 二维码 method 创建.

public static Bitmap 创建(String $文本, Object $宽度高度, Object $二维码颜色, Object $背景颜色, Bitmap $图片) {
    try {
        int $宽高 = 视图.检查大小($宽度高度);
        int $颜色 = 视图.检查颜色($二维码颜色);
        int $背景 = 视图.检查颜色($背景颜色);
        Bitmap $图标 = 转换图标($图片, $宽高, $宽高);
        int $偏移X = $宽高 / 2;
        int $偏移Y = $宽高 / 2;
        int $图标宽 = 0;
        int $图标高 = 0;
        if ($图标 != null) {
            $图标宽 = $图标.getWidth();
            $图标高 = $图标.getHeight();
            $偏移X = ($宽高 - $图标宽) / 2;
            $偏移Y = ($宽高 - $图标高) / 2;
        }
        Hashtable<EncodeHintType, Object> $设置 = new Hashtable<EncodeHintType, Object>();
        $设置.put(EncodeHintType.CHARACTER_SET, "utf-8");
        $设置.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        $设置.put(EncodeHintType.MARGIN, 0);
        BitMatrix $矩阵 = new QRCodeWriter().encode($文本, BarcodeFormat.QR_CODE, $宽高, $宽高, $设置);
        int[] $像素 = new int[$宽高 * $宽高];
        for (int y = 0; y < $宽高; y++) {
            for (int x = 0; x < $宽高; x++) {
                if (x >= $偏移X && x < $偏移X + $图标宽 && y >= $偏移Y && y < $偏移Y + $图标高) {
                    int $单个 = $图标.getPixel(x - $偏移X, y - $偏移Y);
                    if ($单个 == 0) {
                        if ($矩阵.get(x, y)) {
                            $单个 = $颜色;
                        } else {
                            $单个 = $背景;
                        }
                    }
                    $像素[y * $宽高 + x] = $单个;
                } else {
                    if ($矩阵.get(x, y)) {
                        $像素[y * $宽高 + x] = $颜色;
                    } else {
                        $像素[y * $宽高 + x] = $背景;
                    }
                }
            }
        }
        Bitmap $返回 = Bitmap.createBitmap($宽高, $宽高, Bitmap.Config.ARGB_8888);
        $返回.setPixels($像素, 0, $宽高, 0, 0, $宽高, $宽高);
        return $返回;
    } catch (WriterException $错误) {
    }
    return null;
}
Also used : Bitmap(android.graphics.Bitmap) BinaryBitmap(com.google.zxing.BinaryBitmap) QRCodeWriter(com.google.zxing.qrcode.QRCodeWriter) EncodeHintType(com.google.zxing.EncodeHintType) Hashtable(java.util.Hashtable) BitMatrix(com.google.zxing.common.BitMatrix) WriterException(com.google.zxing.WriterException)

Aggregations

BitMatrix (com.google.zxing.common.BitMatrix)32 QRCodeWriter (com.google.zxing.qrcode.QRCodeWriter)32 EncodeHintType (com.google.zxing.EncodeHintType)24 WriterException (com.google.zxing.WriterException)22 Bitmap (android.graphics.Bitmap)19 Hashtable (java.util.Hashtable)12 HashMap (java.util.HashMap)7 BufferedImage (java.awt.image.BufferedImage)6 IOException (java.io.IOException)5 EnumMap (java.util.EnumMap)5 BinaryBitmap (com.google.zxing.BinaryBitmap)4 ErrorCorrectionLevel (com.google.zxing.qrcode.decoder.ErrorCorrectionLevel)4 Graphics2D (java.awt.Graphics2D)4 Color (java.awt.Color)3 Paint (android.graphics.Paint)2 NonNull (android.support.annotation.NonNull)2 Sigchain (co.krypt.krypton.team.Sigchain)2 BarcodeFormat (com.google.zxing.BarcodeFormat)2 BarcodeEncoder (com.journeyapps.barcodescanner.BarcodeEncoder)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2