/** * 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; }
/** * 条形码编码 */ 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; }
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; }
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(); } }
/** * 生成条形二维码 */ 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; }
/** * * @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(); } }
/** * 条形码编码 * <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); } }
/** * 二维码编码 * <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); } }
/** * 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)); }
/** * 将内容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(); } } }
/** * 二维码信息写成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; }
/**二维码的生成*/ 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()); } }
/**条形码的生成*/ 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()); } }
/** * 二维码生成 ,储存地址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; }
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); }
/** * 条形码编码 * * @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(); } }
/** * 二维码编码 * * @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(); } }
/** * 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); }
/** * 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; }
@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()); }
@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); }
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; }
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); } }
@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(); } }
@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(); } }
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); } }
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())))); }
@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(); } }
@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); }
/** *生成二维码图片并保存为文件 * @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); }
/** * 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; }
@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; }
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; } }
/** * 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); } }
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 ""; }
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); }
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(); } }