Java 类com.google.zxing.client.j2se.MatrixToImageWriter 实例源码

项目:IJPay    文件:ZxingKit.java   
/**
 * Zxing图形码生成工具
 *
 * @param contents
 *            内容
 * @param barcodeFormat
 *            BarcodeFormat对象
 * @param format
 *            图片格式,可选[png,jpg,bmp]
 * @param width
 *            宽
 * @param height
 *            高
 * @param margin
 *            边框间距px
 * @param saveImgFilePath
 *            存储图片的完整位置,包含文件名
 * @return {boolean}
 */
public static boolean encode(String contents, BarcodeFormat barcodeFormat, Integer margin,
        ErrorCorrectionLevel errorLevel, String format, int width, int height, String saveImgFilePath) {
    Boolean bool = false;
    BufferedImage bufImg;
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    // 指定纠错等级
    hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
    hints.put(EncodeHintType.MARGIN, margin);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    try {
        // contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height, hints);
        MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
        bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
        bool = writeToFile(bufImg, format, saveImgFilePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bool;
}
项目:framework    文件:BarCodeUtils.java   
/**
 * 条形码编码
 */
public static BufferedImage encode(String contents, int width, int height) {
    int codeWidth = 3 + // start guard
            (7 * 6) + // left bars
            5 + // middle guard
            (7 * 6) + // right bars
            3; // end guard
    codeWidth = Math.max(codeWidth, width);
    try {
        // 原为13位Long型数字(BarcodeFormat.EAN_13),现为128位
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, codeWidth, height, null);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:automat    文件:QrcodeUtil.java   
public static String createQrcode(String dir, String _text) {
    String qrcodeFilePath = "";
    try {
        int qrcodeWidth = 300;
        int qrcodeHeight = 300;
        String qrcodeFormat = "png";
        HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(_text, BarcodeFormat.QR_CODE, qrcodeWidth,
                qrcodeHeight, hints);

        BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
        File qrcodeFile = new File(dir + "/" + UUID.randomUUID().toString() + "." + qrcodeFormat);
        ImageIO.write(image, qrcodeFormat, qrcodeFile);
        MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, qrcodeFile.toPath());
        qrcodeFilePath = qrcodeFile.getAbsolutePath();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return qrcodeFilePath;
}
项目:payment-wechat    文件:ZxingUtil.java   
public static void barCode(String contents,String imgPath,int width, int height) {
    int codeWidth = 3 + // start guard
            (7 * 6) + // left bars
            5 + // middle guard
            (7 * 6) + // right bars
            3; // end guard
    codeWidth = Math.max(codeWidth, width);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,BarcodeFormat.CODE_128, codeWidth, height, null);
        bitMatrix = deleteWhite(bitMatrix);
        MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));
    }catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}
项目:Fetax-AI    文件:CodeUtil.java   
/**
 * 生成条形二维码
 */
public static byte[] encode(String contents, int width, int height, String imgPath) {
    int codeWidth = 3 + // start guard
            (7 * 6) + // left bars
            5 + // middle guard
            (7 * 6) + // right bars
            3; // end guard
    codeWidth = Math.max(codeWidth, width);
    byte[] buf = null;
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                BarcodeFormat.CODE_128, codeWidth, height, null);
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
      ImageIO.write(image, FORMAT_NAME, out);
      out.close();
buf = out.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buf;
}
项目:JavaToolKit    文件:CreateQRCode.java   
/**
 *
 * @param path 完整的路径包括文件名
 * @param width 图片宽
 * @param height 图片高
 * @param contents 内容
 */
public static void createImage(String path,int width,int height,String contents){
    String format = "png";
    //定义二维码的参数
    HashMap hints = new HashMap();
    hints.put(EncodeHintType.AZTEC_LAYERS, "utf-8");//设置编码
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置容错等级: L M Q H
    hints.put(EncodeHintType.MARGIN,1);//设置边距

    //生成文件
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height,hints);
        Path file = new File(path).toPath();
        MatrixToImageWriter.writeToPath(bitMatrix, format, file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:JAVA-    文件:QrcodeUtil.java   
public static String createQrcode(String dir, String _text) {
    String qrcodeFilePath = "";
    try {
        int qrcodeWidth = 300;
        int qrcodeHeight = 300;
        String qrcodeFormat = "png";
        HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(_text, BarcodeFormat.QR_CODE, qrcodeWidth,
                qrcodeHeight, hints);

        BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
        File qrcodeFile = new File(dir + "/" + UUID.randomUUID().toString() + "." + qrcodeFormat);
        ImageIO.write(image, qrcodeFormat, qrcodeFile);
        MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, qrcodeFile.toPath());
        qrcodeFilePath = qrcodeFile.getAbsolutePath();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return qrcodeFilePath;
}
项目:angit    文件:ZxingHelper.java   
/**
 * 条形码编码
 * <p>
 * String imgPath = "target/zxing.png";
 * String contents = "6923450657713";
 * int width = 105, height = 50;
 * ZxingHelper.encode(contents, width, height, imgPath);
 *
 * @param contents 内容
 * @param width    宽度
 * @param height   高度
 * @param imgPath  生成图片路径
 */
public static void encode(String contents, int width, int height, String imgPath) {
    int codeWidth = 3 + // start guard
        (7 * 6) + // left bars
        5 + // middle guard
        (7 * 6) + // right bars
        3; // end guard
    codeWidth = Math.max(codeWidth, width);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
            BarcodeFormat.EAN_13, codeWidth, height, null);

        MatrixToImageWriter
            .writeToPath(bitMatrix, "png", new File(imgPath).toPath());

    } catch (Exception e) {
        LOGGER.error("生成条形码错误", e);
    }
}
项目:angit    文件:ZxingHelper.java   
/**
 * 二维码编码
 * <p>
 * String imgPath2 = "target/zxing2.png";
 * String contents2 = "Hello Zxing!";
 * int width2 = 300, height2 = 300;
 * ZxingHelper.encode2(contents2, width2, height2, imgPath2);
 *
 * @param contents 内容
 * @param width    宽度
 * @param height   高度
 * @param imgPath  生成图片路径
 */
public static void encode2(String contents, int width, int height, String imgPath) {
    EnumMap<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
    // 指定纠错等级
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    // 指定编码格式
    hints.put(EncodeHintType.CHARACTER_SET, "GBK");
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
            BarcodeFormat.QR_CODE, width, height, hints);

        MatrixToImageWriter
            .writeToPath(bitMatrix, "png", new File(imgPath).toPath());

    } catch (Exception e) {
        LOGGER.error("生成二维码错误", e);
    }
}
项目:CryptoPayAPI    文件:CryptoClient.java   
/**
 * Method to get the JavaFX Image QR code for easy input of address
 * @param width width of the image
 * @param height height of the image
 * @return Java FX Image
 * @throws IOException Either when there is an encoding error or java's reserved memory is overwritten.
 * @throws WriterException When ZXING encounters an error.
 */
public Image getQR(int width, int height) throws IOException, WriterException{
    String charset = "UTF-8";
    Map hintMap = new HashMap();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    BitMatrix matrix = new MultiFormatWriter().encode(new String(cryptoAddress.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hintMap);
    MatrixToImageWriter.writeToStream(matrix, "png", stream);
    stream.flush();

    byte[] data = stream.toByteArray();
    stream.close();

    return new Image(new ByteArrayInputStream(data));
}
项目:wish-pay    文件:ZxingUtils.java   
/**
 * 将内容contents生成长为width,宽为width的图片,返回刘文静
 */
public static ServletOutputStream getQRCodeImge(String contents, int width, int height) throws IOException {
    ServletOutputStream stream = null;
    try {
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
        return stream;
    } catch (Exception e) {
        log.error("create QR code error!", e);
        return null;
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
项目:wish-pay    文件:ZxingUtils.java   
/**
 * 二维码信息写成JPG BufferedImage
 *
 * @param content
 * @param width
 * @param height
 * @return
 */
public static BufferedImage writeInfoToJpgBuffImg(String content, int width, int height) {
    if (width < 250) {
        width = 250;
    }
    if (height < 250) {
        height = 250;
    }
    BufferedImage re = null;

    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    Map hints = new HashMap();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    try {
        BitMatrix bitMatrix = multiFormatWriter.encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        re = MatrixToImageWriter.toBufferedImage(bitMatrix);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return re;
}
项目:BasicsProject    文件:ZxingServlet.java   
/**二维码的生成*/
private void createQRCode(HttpServletResponse response){
    /**设置二维码的参数*/
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    // 内容所使用编码
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    // 留白区域大小
    hints.put(EncodeHintType.MARGIN, margin);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,width,height,hints);
        // 输出二维码
        MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());
    } catch (Exception e) {
        System.out.println("生成二维码异常!"+e.toString());
    }
}
项目:BasicsProject    文件:ZxingServlet.java   
/**条形码的生成*/
private void createBarCode(HttpServletResponse response){
    int codeWidth = 3 + // start guard
            (7 * 6) + // left bars
            5 + // middle guard
            (7 * 6) + // right bars
            3; // end guard
    codeWidth = Math.max(codeWidth, width);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.CODE_128, codeWidth, height, null);
        // 条形码
        MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());
    } catch (Exception e) {
        System.out.println("生成条形码异常!"+e.toString());
    }
}
项目:awe-awesomesky    文件:CodeUtil.java   
/**
 * 生成条形二维码
 */
public static byte[] encode(String contents, int width, int height, String imgPath) {
    int codeWidth = 3 + // start guard
            (7 * 6) + // left bars
            5 + // middle guard
            (7 * 6) + // right bars
            3; // end guard
    codeWidth = Math.max(codeWidth, width);
    byte[] buf = null;
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                BarcodeFormat.CODE_128, codeWidth, height, null);
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
      ImageIO.write(image, FORMAT_NAME, out);
      out.close();
buf = out.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buf;
}
项目:Spring-Boot-Server    文件:Qrcode.java   
/**
 * 二维码生成 ,储存地址qrcodeFilePath
 * 
 * @param text 二维码内容
 * @return Base64Code String
 */
@SuppressWarnings("restriction")
public String createQrcode(String text){
    String Imgencode="";
       byte[] imageByte=null;
       String formatName="PNG";
       try {
        //
           int qrcodeWidth = 300;
           int qrcodeHeight = 300;
           HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
           hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
           BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints);

           ByteArrayOutputStream out = new ByteArrayOutputStream();
           BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
           ImageIO.write(bufferedImage, formatName, out);
           imageByte=out.toByteArray();
           Imgencode = new sun.misc.BASE64Encoder().encode(imageByte);
       } catch (Exception e) {
           e.printStackTrace();
       }
       return Imgencode;
   }
项目:OSCAR-ConCert    文件:QrCodeUtils.java   
public static BufferedImage toSingleQrCodeBufferedImage(String s, ErrorCorrectionLevel ec, int scaleFactor) throws WriterException
{
    QRCode qrCode = new QRCode();
    Encoder.encode(s, ec, qrCode);

    BufferedImage bufferedImage=MatrixToImageWriter.toBufferedImage(qrCode.getMatrix());

    if (scaleFactor!=1)
    {
        int newWidth=bufferedImage.getWidth()*scaleFactor;
        int newHeight=bufferedImage.getHeight()*scaleFactor;
        Image image=bufferedImage.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
        bufferedImage=ImageIoUtils.toBufferedImage(image);
    }

    return(bufferedImage);
}
项目:Shop-for-JavaWeb    文件:ZxingHandler.java   
/**
 * 条形码编码
 * 
 * @param contents
 * @param width
 * @param height
 * @param imgPath
 */
public static void encode(String contents, int width, int height, String imgPath) {
    int codeWidth = 3 + // start guard
            (7 * 6) + // left bars
            5 + // middle guard
            (7 * 6) + // right bars
            3; // end guard
    codeWidth = Math.max(codeWidth, width);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                BarcodeFormat.EAN_13, codeWidth, height, null);

        MatrixToImageWriter
                .writeToFile(bitMatrix, "png", new File(imgPath));

    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Shop-for-JavaWeb    文件:ZxingHandler.java   
/**
 * 二维码编码
 * 
 * @param contents
 * @param width
 * @param height
 * @param imgPath
 */
public static void encode2(String contents, int width, int height, String imgPath) {
    Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
    // 指定纠错等级
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    // 指定编码格式
    hints.put(EncodeHintType.CHARACTER_SET, "GBK");
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                BarcodeFormat.QR_CODE, width, height, hints);

        MatrixToImageWriter
                .writeToFile(bitMatrix, "png", new File(imgPath));

    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Camel    文件:BarcodeDataFormat.java   
/**
 * Writes the image file to the output stream.
 *
 * @param graph    the object graph
 * @param exchange the camel exchange
 * @param stream   the output stream
 */
private void printImage(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception {
    final String payload = ExchangeHelper
            .convertToMandatoryType(exchange, String.class, graph);
    final MultiFormatWriter writer = new MultiFormatWriter();

    // set values
    final String type = this.params.getType().toString();

    // create code image  
    final BitMatrix matrix = writer.encode(
            payload,
            this.params.getFormat(),
            this.params.getWidth(),
            this.params.getHeight(),
            writerHintMap);

    // write image back to stream
    MatrixToImageWriter.writeToStream(matrix, type, stream);
}
项目:jfinal-plus    文件:ZxingKit.java   
/**
     * Zxing图形码生成工具
     *
     * @param contents        内容
     * @param barcodeFormat   BarcodeFormat对象
     * @param format          图片格式,可选[png,jpg,bmp]
     * @param width           宽
     * @param height          高
     * @param margin          边框间距px
     * @param saveImgFilePath 存储图片的完整位置,包含文件名
     * @return
     */
    public Boolean encode(String contents, BarcodeFormat barcodeFormat, Integer margin, ErrorCorrectionLevel errorLevel, String format, int width, int height, String saveImgFilePath) {
        Boolean bool;
        BufferedImage bufImg;
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
        hints.put(EncodeHintType.MARGIN, margin);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
//            contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height, hints);
            MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
            bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
            bool = this.writeToFile(bufImg, format, saveImgFilePath);
        } catch (Throwable t) {
            log.error("encode-ex:{}", t);
            throw Throwables.propagate(t);
        }
        return bool;
    }
项目:citizenship-appointment-server    文件:BarcodeController.java   
@RequestMapping(value = "/pdf417/{id}", method = RequestMethod.GET, produces = IMAGE_PNG)
public void barcode417(@PathVariable("id") String id, HttpServletResponse response) throws IOException, WriterException {
    if (!CLIENT_ID_PATTERN.matcher(id).matches()) {
        throw new InputValidationException("Invalid clientId for barcode [" + id + "]");
    }
    response.setContentType(IMAGE_PNG);
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {{
        put(EncodeHintType.MARGIN, MARGIN_PIXELS);
        put(EncodeHintType.ERROR_CORRECTION, 2);
        put(EncodeHintType.PDF417_COMPACT, true);
        put(EncodeHintType.PDF417_COMPACTION, Compaction.TEXT);
    }};
    BitMatrix matrix = new MultiFormatWriter().encode(id, BarcodeFormat.PDF_417, BARCODE_WIDTH, BARCODE_HEIGHT, hints);
    BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
    BufferedImage croppedImage = cropImageWorkaroundDueToZxingBug(bufferedImage);
    ImageIO.write(croppedImage, "PNG", response.getOutputStream());
}
项目:moserp    文件:ProductController.java   
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/{productId}/ean")
public ResponseEntity<?> getProductEAN(@PathVariable String productId) throws WriterException, IOException {
    Product product = repository.findOne(productId);
    if (product == null) {
        return ResponseEntity.notFound().build();
    }
    EAN13Writer ean13Writer = new EAN13Writer();
    BitMatrix matrix = ean13Writer.encode(product.getEan(), BarcodeFormat.EAN_13, 300, 200);
    BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bufferedImage, "png", baos);
    byte[] imageData = baos.toByteArray();
    ByteArrayResource byteArrayResource = new ByteArrayResource(imageData);
    return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(byteArrayResource);
}
项目:youscope    文件:ManageAddDeviceFrame.java   
private void setDriver(String libraryID)
{
    if(libraryID == null)
    {
        this.image = null;
        repaint();
        return;
    }
    BitMatrix matrix;
    try
    {
        matrix = new QRCodeWriter().encode(QR_MESSAGE_PREFIX + libraryID, com.google.zxing.BarcodeFormat.QR_CODE, WIDTH, HEIGHT);
    }
    catch(@SuppressWarnings("unused") WriterException e)
    {
        this.image = null;
        repaint();
        return;
    }

    this.image = MatrixToImageWriter.toBufferedImage(matrix);
    repaint();
    return;
}
项目:metasfresh    文件:BarcodeRestController.java   
private static byte[] toByteArray(final BitMatrix matrix, final String imageFormat)
{
    //
    // Create image from BitMatrix
    final BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);

    // Convert BufferedImage to imageFormat and write it into the stream
    try
    {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, imageFormat, out);
        return out.toByteArray();
    }
    catch (final IOException ex)
    {
        throw new AdempiereException("Failed creating " + imageFormat + " image", ex);
    }

}
项目:eds-starter6-jpa    文件:QRCodeController.java   
@RequireAnyAuthority
@RequestMapping(value = "/qr", method = RequestMethod.GET)
public void qrcode(HttpServletResponse response,
        @AuthenticationPrincipal JpaUserDetails jpaUserDetails)
        throws WriterException, IOException {

    User user = jpaUserDetails.getUser(this.jpaQueryFactory);
    if (user != null && StringUtils.hasText(user.getSecret())) {
        response.setContentType("image/png");
        String contents = "otpauth://totp/" + user.getEmail() + "?secret="
                + user.getSecret() + "&issuer=" + this.appName;

        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix matrix = writer.encode(contents, BarcodeFormat.QR_CODE, 200, 200);
        MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
        response.getOutputStream().flush();
    }
}
项目:eds-starter6-mongodb    文件:QRCodeController.java   
@RequireAnyAuthority
@RequestMapping(value = "/qr", method = RequestMethod.GET)
public void qrcode(HttpServletResponse response,
        @AuthenticationPrincipal MongoUserDetails userDetails)
        throws WriterException, IOException {

    User user = userDetails.getUser(this.mongoDb);
    if (user != null && StringUtils.hasText(user.getSecret())) {
        response.setContentType("image/png");
        String contents = "otpauth://totp/" + user.getEmail() + "?secret="
                + user.getSecret() + "&issuer=" + this.appName;

        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix matrix = writer.encode(contents, BarcodeFormat.QR_CODE, 200, 200);
        MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
        response.getOutputStream().flush();
    }
}
项目:actframework    文件:ZXingResult.java   
private void renderCode(H.Response response) {
    response.contentType("image/png");
    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, Act.appConfig().encoding());
    hints.put(EncodeHintType.MARGIN, 0);
    ErrorCorrectionLevel level = errorCorrectionLevel();
    if (null != level) {
        hints.put(EncodeHintType.ERROR_CORRECTION, level);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    try {
        BitMatrix bitMatrix = writer.encode(getMessage(), barcodeFormat(), width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", response.outputStream());
    } catch (Exception e) {
        throw E.unexpected(e);
    }
}
项目:drone-slam    文件:QRCodeGeneratorPanel.java   
private void generateQRCode(String contents) {
        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = writer.encode(contents, BarcodeFormat.QR_CODE, Integer.parseInt(width.getText()), Integer.parseInt(height.getText()));
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);

            setImage(image);
        } catch (WriterException e) {
            e.printStackTrace();
        }

//      setSize(new Dimension(Math.min(300, Integer.parseInt(width.getText())), Math.min(400, Integer.parseInt(height.getText()))));
//      setPreferredSize(new Dimension(Math.min(300, Integer.parseInt(width.getText())), Math.min(400, Integer.parseInt(height.getText()))));
//      setMinimumSize(new Dimension(Math.min(300, Integer.parseInt(width.getText())), Math.min(400, Integer.parseInt(height.getText()))));
//      setMaximumSize(new Dimension(Math.min(300, Integer.parseInt(width.getText())), Math.min(400, Integer.parseInt(height.getText()))));
    }
项目:springsecuritytotp    文件:QRCodeController.java   
@RequestMapping(value = "/qrcode/{username}.png", method = RequestMethod.GET)
public void qrcode(HttpServletResponse response,
        @PathVariable("username") String username)
        throws WriterException, IOException {

    User user = this.userRepository.findByUserName(username);
    if (user != null) {
        response.setContentType("image/png");
        String contents = "otpauth://totp/" + username + ":" + user.getEmail()
                + "?secret=" + user.getSecret() + "&issuer=SpringSecurityTOTP";

        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix matrix = writer.encode(contents, BarcodeFormat.QR_CODE, 200, 200);
        MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
        response.getOutputStream().flush();
    }
}
项目:nordpos    文件:PrintItemBarcode.java   
@Override
public void draw(Graphics2D g, int x, int y, int width) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform oldt = g2d.getTransform();
    g2d.translate(x - 10 + (width - (int) (m_iWidth * scale)) / 2, y + 10);
    g2d.scale(scale, scale);

    try {
        if (m_qrMatrix != null) {
            com.google.zxing.Writer writer = new QRCodeWriter();
            m_qrMatrix = writer.encode(m_sCode, com.google.zxing.BarcodeFormat.QR_CODE, m_iWidth, m_iHeight);
            g2d.drawImage(MatrixToImageWriter.toBufferedImage(m_qrMatrix), null, 0, 0);
        } else if (m_barcode != null) {
            m_barcode.generateBarcode(new Java2DCanvasProvider(g2d, 0), m_sCode);
        }
    } catch (IllegalArgumentException | WriterException ex) {
        g2d.drawRect(0, 0, m_iWidth, m_iHeight);
        g2d.drawLine(0, 0, m_iWidth, m_iHeight);
        g2d.drawLine(m_iWidth, 0, 0, m_iHeight);
    }

    g2d.setTransform(oldt);
}
项目:arong    文件:QrCodeUtil.java   
/**
 *生成二维码图片并保存为文件
 * @param content 文本内容
 * @param output 目标文件
 * @param format 图片格式
 * @param width 宽
 * @param height 高
 * @throws WriterException
 * @throws IOException
 */
public static void genQrCodeToFile(String content, File output, String format, Integer width,
                                   Integer height) throws WriterException, IOException {

    if (width == null) {
        width = QrCodeUtil.width; // 图像宽度
    }
    if (height == null) {
        height = QrCodeUtil.height; // 图像高度
    }
    if (format == null) {
        format = QrCodeUtil.format; //文件格式
    }
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    BitMatrix bitMatrix =
        new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); // 生成矩阵
    MatrixToImageWriter.writeToFile(bitMatrix, format, output);
}
项目:spayd    文件:SpaydQRFactory.java   
/**
 * Generate a QR code with the payment information of a given size, optionally, with branded
 * @param paymentString A SPAYD string with payment information
 * @return An image with the payment QR code
 * @throws SpaydQRException
 */
public BufferedImage createQRCode(String paymentString) {
    notEmpty(paymentString);

    final BitMatrix matrix;
    final int barsize;
    final Writer writer = new MultiFormatWriter();
    try {
        final Map<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1");
        final QRCode code = Encoder.encode(paymentString, ErrorCorrectionLevel.M, hints);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        barsize = size / (code.getMatrix().getWidth() + 8);
        matrix = writer.encode(paymentString, BarcodeFormat.QR_CODE, size, size, hints);
    } catch (WriterException e) {
        throw new SpaydQRException("Unable to create QR code", e);
    }

    final BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);

    return isBranded() ? brandImage(image, barsize) : image;
}
项目:StreamingQR    文件:RandomQRDecodeTest.java   
@Parameters(name = "{0}")
public static Collection<Object[]> setup() {
  List<Object[]> qrcodes = Lists.newArrayList();

  long seed = System.currentTimeMillis();
  Random rand = new Random(seed);
  for(int i = 0; i < COUNT; i++ ){
    byte[] bytes = new byte[nextNatural(rand) % 2048];
    rand.nextBytes(bytes);
    int height = 200 + (nextNatural(rand) % 7) * 100;
    int width = 200 + (nextNatural(rand) % 7) * 100;

    Transmit t = new Transmit(height, width);
    BitMatrix bmap = t.bytesToQRCode(bytes, ErrorCorrectionLevel.L);

    BufferedImage newCode = MatrixToImageWriter.toBufferedImage(bmap);

    qrcodes.add(new Object[] { "seed: "+ seed + ": "+i
                             , newCode
    });
  }
  return qrcodes;
}
项目:Eye-Fi    文件:EyeFi.java   
public BufferedImage makeQRCode(byte[] data) {

        try {
            Hashtable<EncodeHintType, ErrorCorrectionLevel> hints = new Hashtable<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, (errorCorrectionLevel == 0) ? ErrorCorrectionLevel.L
                    : (errorCorrectionLevel == 1) ? ErrorCorrectionLevel.M
                            : (errorCorrectionLevel == 2) ? ErrorCorrectionLevel.Q
                                    : (errorCorrectionLevel == 3) ? ErrorCorrectionLevel.H
                                            : null);
            BitMatrix matrix = new QRCodeWriter().encode(new String(data, Charset.forName("ISO-8859-1")),
                    com.google.zxing.BarcodeFormat.QR_CODE, QRSize, QRSize, hints);
            dataSendLength = data.length;
            qrCode = MatrixToImageWriter.toBufferedImage(matrix);
            return qrCode;
        } catch (WriterException ex) {
            ex.printStackTrace();
            return null;
        }
    }
项目:oscar-old    文件:QrCodeUtils.java   
public static BufferedImage toSingleQrCodeBufferedImage(String s, ErrorCorrectionLevel ec, int scaleFactor) throws WriterException
{
    QRCode qrCode = new QRCode();
    Encoder.encode(s, ec, qrCode);

    BufferedImage bufferedImage=MatrixToImageWriter.toBufferedImage(qrCode.getMatrix());

    if (scaleFactor!=1)
    {
        int newWidth=bufferedImage.getWidth()*scaleFactor;
        int newHeight=bufferedImage.getHeight()*scaleFactor;
        Image image=bufferedImage.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
        bufferedImage=ImageIoUtils.toBufferedImage(image);
    }

    return(bufferedImage);
}
项目:STAR-Vote    文件:PrintImageUtils.java   
/**
 * A method for generating a barcode of some text
 *
 * @param string        the string to be converted to barcode, will be a bid in this case
 * @return              an image representing the barcode to be drawn on a ballot
 */
public static BufferedImage getBarcode(String string){

    /* Try to encode the string as a barcode */
    try {

        Code128Writer writer = new Code128Writer();
        BitMatrix bar = writer.encode(string, BarcodeFormat.CODE_128, 264, 48, new HashMap<EncodeHintType,Object>());

        return MatrixToImageWriter.toBufferedImage(bar);
    }
    catch (WriterException e){ throw new RuntimeException(e); }

}
项目:iBase4J-Common    文件:QrcodeUtil.java   
public static String createQrcode(String dir, String content, int width, int height) {
    try {
        String qrcodeFormat = "png";
        HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        File file = new File(dir, UUID.randomUUID().toString() + "." + qrcodeFormat);
        MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, file.toPath());
        return file.getAbsolutePath();
    } catch (Exception e) {
        logger.error("", e);
    }
    return "";
}
项目:digital-display-garden-iteration-4-revolverenguardia-1    文件:QRCodes.java   
public static BufferedImage createQRCode(String qrCodeData, String charset, Map hintMap, int qrCodeheight, int qrCodewidth)
        throws WriterException, IOException {
    //Create the BitMatrix representing the QR code
    BitMatrix matrix = new MultiFormatWriter().encode(
            new String(qrCodeData.getBytes(charset), charset),
            BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);

    //Create BufferedImages from the QRCode BitMatricies
    return MatrixToImageWriter.toBufferedImage(matrix);
}
项目:payment-wechat    文件:ZxingUtil.java   
public static void qrCode(int width,int height,String content,String suffix,String imgPath){
    Hashtable<EncodeHintType, String> hints= new Hashtable<EncodeHintType, String>();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    BitMatrix bitMatrix;
    try {
        bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
        bitMatrix = deleteWhite(bitMatrix);
File outputFile = new File(imgPath);
        MatrixToImageWriter.writeToFile(bitMatrix, suffix, outputFile);
    } catch (Exception e) {
        e.printStackTrace();
    }
 }