public static Bitmap getQR(final byte[] content, final int size) { final QRCodeWriter writer = new QRCodeWriter(); try { final Map<EncodeHintType, Object> encodingHints = new HashMap<>(); encodingHints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); encodingHints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); final BitMatrix encoding = writer.encode(Utils.makeQR(content), BarcodeFormat.QR_CODE, size, size, encodingHints); final Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { bitmap.setPixel(i, j, encoding.get(i, j) ? COLOR_DARK : COLOR_LIGHT); } } return bitmap; } catch (WriterException e) { Log.e("QRUtils", "Failed to get QR code", e); } return null; }
/** * 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; }
/** * 创建二维码 * * @param size 二维码尺寸 * @param content 二维码内容 * @param logoPath Logo地址 * @param needCompress 是否压缩 * @return * @throws Exception */ private static BufferedImage createImage(int size, String content, String logoPath, boolean needCompress) throws Exception { Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (logoPath == null || "".equals(logoPath)) { return image; } // 插入图片 QRCodeUtils.insertImage(size, image, logoPath, needCompress); return image; }
/** * 根据内容生成二维码数据 * @param content 二维码文字内容[为了信息安全性,一般都要先进行数据加密] * @param width 二维码照片宽度 * @param height 二维码照片高度 * @return */ public static BitMatrix createQRCode(String content, int width, int height){ Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); //设置字符编码 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定纠错等级 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.MARGIN, 1); BitMatrix matrix = null; try { matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); } catch (WriterException e) { e.printStackTrace(); } return matrix; }
/** * 根据内容生成二维码数据 * * @param content 二维码文字内容[为了信息安全性,一般都要先进行数据加密] * @param length 二维码图片宽度和高度 */ private static BitMatrix createQrcodeMatrix(String content, int length) { Map<EncodeHintType, Object> hints = Maps.newEnumMap(EncodeHintType.class); // 设置字符编码 hints.put(EncodeHintType.CHARACTER_SET, Charsets.UTF_8.name()); // 指定纠错等级 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); try { return new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, length, length, hints); } catch (Exception e) { logger.warn("内容为:【" + content + "】的二维码生成失败!", e); return null; } }
private static int chooseMaskPattern(BitArray bits, ErrorCorrectionLevel ecLevel, Version version, ByteMatrix matrix) throws WriterException { int minPenalty = Integer.MAX_VALUE; // Lower penalty is better. int bestMaskPattern = -1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; }
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException { // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.getTotalCodewords(); // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.getTotalECCodewords(); // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; int totalInputBytes = (numInputBits + 7) / 8; if (numDataBytes >= totalInputBytes) { return version; } } throw new WriterException("Data too big"); }
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitArray maskBits = new BitArray(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.getSize() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.getSize()); } }
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException { if (contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } else if (format != BarcodeFormat.QR_CODE) { throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format); } else if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } else { ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; int quietZone = 4; if (hints != null) { ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION); if (requestedECLevel != null) { errorCorrectionLevel = requestedECLevel; } Integer quietZoneInt = (Integer) hints.get(EncodeHintType.MARGIN); if (quietZoneInt != null) { quietZone = quietZoneInt.intValue(); } } return renderResult(Encoder.encode(contents, errorCorrectionLevel, hints), width, height, quietZone); } }
public Bitmap generate(String text, int width, int height) { Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); try { BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (bitMatrix.get(j, i)) { pixels[i * width + j] = 0x00000000; } else { pixels[i * height + j] = 0xffffffff; } } } Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565); bitmap = addLogo(bitmap); return bitmap; } catch (WriterException e) { e.printStackTrace(); } return null; }
private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception { Hashtable hints = new Hashtable(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (imgPath == null || "".equals(imgPath)) { return image; } // 插入图片 CodeUtil.insertImage(image, imgPath, needCompress); return image; }
private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception { Hashtable hints = new Hashtable(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (imgPath == null || "".equals(imgPath)) { return image; } // 插入图片 QRCodeUtil.insertImage(image, imgPath, needCompress); return image; }
/** * * @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(); } }
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) throws WriterException { if (QRCode.isValidMaskPattern(maskPattern)) { int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); bits.appendBits(calculateBCHCode(typeInfo, TYPE_INFO_POLY), 10); BitArray maskBits = new BitArray(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.getSize() != 15) { throw new WriterException("should not happen but we got: " + bits.getSize()); } return; } throw new WriterException("Invalid mask pattern"); }
public static String getQr(String text) { String s = "生成二维码失败"; int width = 40; int height = 40; // 用于设置QR二维码参数 Hashtable<EncodeHintType, Object> qrParam = new Hashtable<EncodeHintType, Object>(); // 设置QR二维码的纠错级别——这里选择最低L级别 qrParam.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); qrParam.put(EncodeHintType.CHARACTER_SET, "utf-8"); try { BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, qrParam); s = toAscii(bitMatrix); } catch (WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; }
public Bitmap generateQRCode(String text) { Bitmap bmp = null; Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage int size = 256; BitMatrix bitMatrix = null; try { bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hintMap); int width = bitMatrix.getWidth(); bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565); for (int x = 0; x < width; x++) { for (int y = 0; y < width; y++) { bmp.setPixel(y, x, bitMatrix.get(x, y) == true ? Color.BLACK : Color.WHITE); } } } catch (WriterException e) { e.printStackTrace(); } return bmp; }
/** * 二维码编码 * <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)); }
public QRCodeMaker (List<String> beds) throws WriterException, IOException { String url; String bedPath; Map hintMap = new HashMap(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); System.out.println(System.getProperty("user.dir")); System.out.println("About to create the directory"); File imageDirectory = new File(imageDirectoryPath); imageDirectory.delete(); imageDirectory.mkdir(); System.out.println("Made the directory: " + imageDirectoryPath); for (String bed : beds){ bedPath = imageDirectoryPath + bed + ".jpg"; url = "http://174.138.66.146:9000/api/" + bed; createQRCode(url, bedPath, charset, hintMap, 500, 500); } }
/** * 将内容contents生成长为width,宽为width的图片,图片路径由imgPath指定 */ public static File getQRCodeImge(String contents, int width, int height, String imgPath) { 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); File imageFile = new File(imgPath); writeToFile(bitMatrix, "png", imageFile); return imageFile; } catch (Exception e) { log.error("create QR code error!", e); return null; } }
/** * 将内容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(); } } }
public static Bitmap createQRCode(String content, int widthAndHeight) { if (TextUtils.isEmpty(content)) return null; try { Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //Fault tolerance level. MAX hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //Set the width of the blank margin. hints.put(EncodeHintType.MARGIN, 0); BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight); int width = matrix.getWidth(); int height = matrix.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (WriterException e) { e.printStackTrace(); } return null; }
@SuppressLint("SetTextI18n") private void quickEdit(boolean clear) { mEdtContent.setText(clear ? "" : "https://github.com/Ydcool/QrModule"); mEdtSize.setText(clear ? "" : "400"); mEdtMargin.setText(clear ? "" : "2"); mEdtColorR.setText(clear ? "" : "65"); mEdtColorG.setText(clear ? "" : "82"); mEdtColorB.setText(clear ? "" : "172"); mEdtColorBgR.setText(clear ? "" : "233"); mEdtColorBgG.setText(clear ? "" : "233"); mEdtColorBgB.setText(clear ? "" : "233"); mSpinnerEcc.setSelection(ErrorCorrectionLevel.H.ordinal(), true); mOverlayEnabled = !clear; mTbOverlay.setChecked(!clear); mEdtOverlaySize.setText(clear ? "" : "100"); mEdtOverlayAplha.setText(clear ? "" : "255"); mXfermode = PorterDuff.Mode.SRC_ATOP; mSpinnerXfermode.setSelection(PorterDuff.Mode.SRC_ATOP.ordinal(), true); if (clear) mImgQrGenerated.setImageResource(R.drawable.ic_default_qr); }
/** * 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; }
/** * 生成二维码 * @param content 源内容 * @param imgPath 生成二维码保存的路径 * @param needCompress 是否要压缩 * @return 返回二维码图片 * @throws Exception */ private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception { Hashtable hints = new Hashtable(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (imgPath == null || "".equals(imgPath)) { return image; } // 插入图片 QRCodeUtil.insertImage(image, imgPath, needCompress); return image; }
public static Bitmap create2dBarcodeBitmap(String input, int size) { try { final QRCodeWriter barcodeWriter = new QRCodeWriter(); final Hashtable<EncodeHintType, Object> hints = new Hashtable<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); final BitMatrix result = barcodeWriter.encode(input, BarcodeFormat.QR_CODE, size, size, hints); final int width = result.getWidth(); final int height = result.getHeight(); final int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { final int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE; } } final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (final Exception e) { e.printStackTrace(); return null; } }