Search in sources :

Example 11 with MatrixToImageConfig

use of com.google.zxing.client.j2se.MatrixToImageConfig in project java-apply by javachengwc.

the class ZXingUtil method encodeQRCodeImage.

/**
 * 生成二维码
 * @param content   二维码内容
 * @param charset   编码二维码内容时采用的字符集(传null时默认采用UTF-8编码)
 * @param imagePath 二维码图片存放路径(含文件名)
 * @param width     生成的二维码图片宽度
 * @param height    生成的二维码图片高度
 * @param logoPath  logo头像存放路径(含文件名,若不加logo则传null即可)
 * @return 生成二维码结果(true or false)
 */
public static boolean encodeQRCodeImage(String content, String charset, String imagePath, int width, int height, String logoPath) {
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    // 指定编码格式
    // hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    // 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    // 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
    BitMatrix bitMatrix = null;
    try {
        bitMatrix = new MultiFormatWriter().encode(new String(content.getBytes(charset == null ? "UTF-8" : charset), "ISO-8859-1"), BarcodeFormat.QR_CODE, width, height, hints);
    } catch (Exception e) {
        System.out.println("编码待生成二维码图片的文本时发生异常,堆栈轨迹如下");
        e.printStackTrace();
        return false;
    }
    // 生成的二维码图片默认背景为白色,前景为黑色,但是在加入logo图像后会导致logo也变为黑白色,至于是什么原因还没有仔细去读它的源码
    // 所以这里对其第一个参数黑色将ZXing默认的前景色0xFF000000稍微改了一下0xFF000001,最终效果也是白色背景黑色前景的二维码,且logo颜色保持原有不变
    MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
    // 这里要显式指定MatrixToImageConfig,否则还会按照默认处理将logo图像也变为黑白色(如果打算加logo的话,反之则不须传MatrixToImageConfig参数)
    try {
        MatrixToImageWriter.writeToFile(bitMatrix, imagePath.substring(imagePath.lastIndexOf(".") + 1), new File(imagePath), config);
    } catch (IOException e) {
        System.out.println("生成二维码图片[" + imagePath + "]时遇到异常,堆栈轨迹如下");
        e.printStackTrace();
        return false;
    }
    // 此时二维码图片已经生成了,只不过没有logo头像,所以接下来根据传入的logoPath参数来决定是否加logo头像
    if (null == logoPath) {
        return true;
    } else {
        // 即private static void overlapImage(BufferedImage image, String imagePath, String logoPath)
        try {
            // 这里不需要判断logoPath是否指向了一个具体的文件,因为这种情景下overlapImage会抛IO异常
            overlapImage(imagePath, logoPath);
            return true;
        } catch (IOException e) {
            System.out.println("为二维码图片[" + imagePath + "]添加logo头像[" + logoPath + "]时遇到异常,堆栈轨迹如下");
            e.printStackTrace();
            return false;
        }
    }
}
Also used : EncodeHintType(com.google.zxing.EncodeHintType) HashMap(java.util.HashMap) MultiFormatWriter(com.google.zxing.MultiFormatWriter) BitMatrix(com.google.zxing.common.BitMatrix) MatrixToImageConfig(com.google.zxing.client.j2se.MatrixToImageConfig) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException) NotFoundException(com.google.zxing.NotFoundException)

Example 12 with MatrixToImageConfig

use of com.google.zxing.client.j2se.MatrixToImageConfig in project i2pplus by vituperative.

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 > 1024)
                size = 1024;
        } 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) {
                // add 1 so it generates RGB instead of 1 bit,
                // so text anti-aliasing works
                MatrixToImageConfig cfg = new MatrixToImageConfig(MatrixToImageConfig.BLACK + 1, MatrixToImageConfig.WHITE);
                BufferedImage bi = MatrixToImageWriter.toBufferedImage(matrix, cfg);
                Graphics2D g = bi.createGraphics();
                // anti-aliasing and hinting for the text
                // 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_PURE);
                // 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);
                // scale font
                int width = bi.getWidth();
                int height = bi.getHeight();
                float shrink = Math.min(1.0f, 14.0f / text.length());
                if (width >= 256)
                    shrink = Math.min(1.0f, 16.0f / text.length());
                int pts = Math.round(shrink * 16.0f * size / 160);
                if (width >= 256)
                    pts = Math.round(shrink * 16.0f * size / 180);
                Font font = new Font(DEFAULT_FONT_NAME, Font.BOLD, pts);
                g.setFont(font);
                Color color = Color.BLACK;
                g.setColor(color);
                double swidth = font.getStringBounds(text, 0, text.length(), g.getFontRenderContext()).getBounds().getWidth();
                int x = (width - (int) swidth) / 2;
                int y = height - 10;
                if (height >= 256)
                    y = height - ((height / 50) + 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.setHeader("Cache-control", "max-age=2628000, immutable");
        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) MatrixToImageConfig(com.google.zxing.client.j2se.MatrixToImageConfig) 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 13 with MatrixToImageConfig

use of com.google.zxing.client.j2se.MatrixToImageConfig in project cobnet by LilPoppy.

the class QRCodeProvider method encode.

public BufferedImage encode(String text, BufferedImage logo, int width, int height, Pair<Color, Color> colors, Map.Entry<EncodeHintType, ?>... options) throws WriterException, NotFoundException {
    BitMatrix matrix = encode(text, width, height, options);
    BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix, new MatrixToImageConfig(colors.getFirst().getRGB(), colors.getSecond().getRGB()));
    int deltaHeight = image.getHeight() - logo.getHeight();
    int deltaWidth = image.getWidth() - logo.getWidth();
    BufferedImage combined = new BufferedImage(image.getHeight(), image.getWidth(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = (Graphics2D) combined.getGraphics();
    graphics.drawImage(image, 0, 0, null);
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
    graphics.drawImage(logo, Math.round((float) deltaWidth / 2), Math.round((float) deltaHeight / 2), null);
    return combined;
}
Also used : BitMatrix(com.google.zxing.common.BitMatrix) MatrixToImageConfig(com.google.zxing.client.j2se.MatrixToImageConfig) BufferedImage(java.awt.image.BufferedImage)

Example 14 with MatrixToImageConfig

use of com.google.zxing.client.j2se.MatrixToImageConfig in project cobnet by LilPoppy.

the class QRCodeProvider method encode.

public byte[] encode(String text, int width, int height, String format, Pair<Color, Color> colors, Map.Entry<EncodeHintType, ?>... options) throws WriterException, IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(encode(text, width, height, options), format, stream, new MatrixToImageConfig(colors.getFirst().getRGB(), colors.getFirst().getRGB()));
    return stream.toByteArray();
}
Also used : MatrixToImageConfig(com.google.zxing.client.j2se.MatrixToImageConfig)

Example 15 with MatrixToImageConfig

use of com.google.zxing.client.j2se.MatrixToImageConfig in project openhtmltopdf by danfickle.

the class ZXingObjectDrawer method drawObject.

@Override
public Map<Shape, String> drawObject(Element e, double x, double y, double width, double height, OutputDevice outputDevice, RenderingContext ctx, int dotsPerPixel) {
    MultiFormatWriter mfw = new MultiFormatWriter();
    int onColor = e.hasAttribute("on-color") ? parseInt(e.getAttribute("on-color"), MatrixToImageConfig.BLACK) : MatrixToImageConfig.BLACK;
    int offColor = e.hasAttribute("off-color") ? parseInt(e.getAttribute("off-color"), MatrixToImageConfig.WHITE) : MatrixToImageConfig.WHITE;
    Map<EncodeHintType, Object> encodeHints = new EnumMap<>(EncodeHintType.class);
    // default
    encodeHints.put(EncodeHintType.MARGIN, 0);
    NodeList childNodes = e.getChildNodes();
    int childNodesCount = childNodes.getLength();
    for (int i = 0; i < childNodesCount; i++) {
        Node n = childNodes.item(i);
        if (!(n instanceof Element))
            continue;
        Element eChild = (Element) n;
        if (!"encode-hint".equals(eChild.getTagName())) {
            continue;
        }
        EncodeHintType encodeHintType = safeEncodeHintTypeValueOf(eChild.getAttribute("name"));
        Object value = encodeHintType != null ? handleValueForHint(encodeHintType, eChild.getAttribute("value")) : null;
        if (encodeHintType != null && value != null) {
            encodeHints.put(encodeHintType, value);
        }
    }
    String value = e.getAttribute("value");
    BarcodeFormat barcodeFormat = e.hasAttribute("format") ? BarcodeFormat.valueOf(e.getAttribute("format")) : BarcodeFormat.QR_CODE;
    int finalWidth = (int) (width / dotsPerPixel);
    int finalHeight = (int) (height / dotsPerPixel);
    try {
        BitMatrix bitMatrix = mfw.encode(value, barcodeFormat, finalWidth, finalHeight, encodeHints);
        outputDevice.drawWithGraphics((float) x, (float) y, (float) width, (float) height, graphics2D -> {
            // generating a vector from the bitmatrix don't seems to be straightforward, thus a bitmap image...
            graphics2D.drawImage(MatrixToImageWriter.toBufferedImage(bitMatrix, new MatrixToImageConfig(onColor, offColor)), 0, 0, finalWidth, finalHeight, null);
        });
    } catch (WriterException we) {
        XRLog.log(Level.WARNING, LogMessageId.LogMessageId1Param.GENERAL_MESSAGE, "Error while generating the barcode", we);
    }
    return null;
}
Also used : BarcodeFormat(com.google.zxing.BarcodeFormat) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) BitMatrix(com.google.zxing.common.BitMatrix) MatrixToImageConfig(com.google.zxing.client.j2se.MatrixToImageConfig) SymbolShapeHint(com.google.zxing.datamatrix.encoder.SymbolShapeHint) EncodeHintType(com.google.zxing.EncodeHintType) MultiFormatWriter(com.google.zxing.MultiFormatWriter) WriterException(com.google.zxing.WriterException)

Aggregations

MatrixToImageConfig (com.google.zxing.client.j2se.MatrixToImageConfig)17 BitMatrix (com.google.zxing.common.BitMatrix)13 BufferedImage (java.awt.image.BufferedImage)10 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 WriterException (com.google.zxing.WriterException)5 QRCodeWriter (com.google.zxing.qrcode.QRCodeWriter)5 MultiFormatWriter (com.google.zxing.MultiFormatWriter)4 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 EncodeHintType (com.google.zxing.EncodeHintType)3 Color (java.awt.Color)3 Font (java.awt.Font)3 Graphics2D (java.awt.Graphics2D)3 File (java.io.File)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Image (javafx.scene.image.Image)2 BarcodeFormat (com.google.zxing.BarcodeFormat)1 NotFoundException (com.google.zxing.NotFoundException)1 SymbolShapeHint (com.google.zxing.datamatrix.encoder.SymbolShapeHint)1 ImportException (com.sparrowwallet.sparrow.io.ImportException)1