public class QrCodeUtil { /** * 生成包含字符串信息的二维码图片 * @param outputStream 文件输出流路径 * @param content 二维码携带信息 * @param qrCodeSize 二维码图片大小 * @param imageFormat 二维码的格式 * @throws WriterException * @throws IOException */ public static boolean generateQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException { // 设置二维码纠错级别Map Hashtable hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别 QRCodeWriter qrCodeWriter = new QRCodeWriter(); // 创建比特矩阵(位矩阵)的QR码编码的字符串 BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap); // 去除空白区域 byteMatrix = deleteWhite(byteMatrix); // 使BufferedImage勾画QRCode int matrixWidth = byteMatrix.getWidth(); BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB); // 使用比特矩阵画并保存图像 for (int i = 0; i < matrixWidth; i++) { for (int j = 0; j < matrixWidth; j++) { image.setRGB(i, j, byteMatrix.get(i, j) ? Color.BLACK.getRGB() : Color.WHITE.getRGB()); } } return ImageIO.write(image, imageFormat, outputStream); } /** * 去除空白区域 * @param matrix * @return */ public static BitMatrix deleteWhite(BitMatrix matrix) { int[] rec = matrix.getEnclosingRectangle(); int resWidth = rec[2] + 1; int resHeight = rec[3] + 1; BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); resMatrix.clear(); for (int i = 0; i < resWidth; i++) { for (int j = 0; j < resHeight; j++) { if (matrix.get(i + rec[0], j + rec[1])) resMatrix.set(i, j); } } return resMatrix; } /** * 读二维码并输出携带的信息 * @param inputStream * @throws IOException */ public static Result readQrCode(InputStream inputStream) throws IOException { // 从输入流中获取字符串信息 BufferedImage image = ImageIO.read(inputStream); // 将图像转换为二进制位图源 LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); Result result = null; try { result = reader.decode(bitmap); } catch (ReaderException e) { e.printStackTrace(); } return result; } } |
|
来自: 昵称11935121 > 《待分类》