/** * 生成二维码或者条形码工具类 * * @author chb * */ public class CodeUtil { private static String[] arr = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; private static Logger logger = Logger.getLogger(CodeUtil.class); private static String format = "png"; /** * 生成二维码(QR类型) * * @param content * 二维码文本内容 * @param file * 生成的路径(文件路径) * @return 返回文件路径加文件全名称 */ public static String getQRCode(String content, String file) { try { if (null == content || content.equals("")) { logger.error("CodeUtil.class-->getQRCode()-->content is null"); } int width = 300; int height = 300; HashMap<EncodeHintType, String> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 二维码的格式是BarcodeFormat.QR_CODE qr类型二维码 BarcodeFormat.DATA_MATRIX dm码 BitMatrix qrc = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); File out = new File(file + "/" + getFileName()); // 生成二维码图片 WriteBitMatricToFile.writeBitMatricToFile(qrc, format, out); WriteBitMatricToFile.parseCode(out); logger.info(out.getAbsolutePath()); return out.getAbsolutePath(); } catch (Exception e) { logger.error(e.getMessage()); return null; } } /** * 生成条形码 * * @param content * 二维码文本内容 * @param file * 生成的路径(文件路径) * @return 返回文件路径加文件全名称 */ public static String getBarCode(String content, String file) { try { if (null == content || content.equals("")) { logger.error("CodeUtil.class-->getQRCode()-->content is null"); return null; } int len = content.trim().length(); if (len != 12 && len != 13) { logger.error("CodeUtil.class-->getQRCode()-->content length fail (12 or 13,fact " + len + ")"); return null; } int width = 105; int height = 50; HashMap<EncodeHintType, String> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 条形码的格式是 BarcodeFormat.EAN_13 BitMatrix bc = new MultiFormatWriter().encode(content, BarcodeFormat.EAN_13, width, height, hints); File out = new File(file + "/" + getFileName()); // 输出图片 WriteBitMatricToFile.writeBitMatricToFile(bc, format, out); WriteBitMatricToFile.parseCode(out); // 记录日志 logger.info(out.getAbsolutePath()); return out.getAbsolutePath(); } catch (Exception e) { logger.error(e.getMessage()); return null; } } private static String getFileName() { // 随机生成26以内的正整数 int next = (int) Math.floor(Math.random() * 26); // 生成文件的名称,当前时间毫秒数+一个随机字母+后缀 return System.currentTimeMillis() + arr[next] + "." + format; } /** * 解析二维码中的信息 * * @param filePath * @return 二维码中文本 */ public static String parseQRCode(String filePath) { String content = ""; try { File file = new File(filePath); BufferedImage image = ImageIO.read(file); LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map<DecodeHintType, Object> hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); MultiFormatReader formatReader = new MultiFormatReader(); Result result = formatReader.decode(binaryBitmap, hints); System.out.println("result 为:" + result.toString()); System.out.println("resultFormat 为:" + result.getBarcodeFormat()); System.out.println("resultText 为:" + result.getText()); // 设置返回值 content = result.getText(); } catch (Exception e) { e.printStackTrace(); } return content; } }
public class WriteBitMatricToFile { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private static BufferedImage toBufferedImage(BitMatrix bm) { int width = bm.getWidth(); int height = bm.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { image.setRGB(i, j, bm.get(i, j) ? BLACK : WHITE); } } return image; } public static void writeBitMatricToFile(BitMatrix bm, String format, File file) { BufferedImage image = toBufferedImage(bm); try { if (!ImageIO.write(image, format, file)) { throw new RuntimeException("Can not write an image to file" + file); } } catch (IOException e) { e.printStackTrace(); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public static void parseCode(File file) { try { MultiFormatReader formatReader = new MultiFormatReader(); if (!file.exists()) { return; } BufferedImage image = ImageIO.read(file); LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); Result result = formatReader.decode(binaryBitmap, hints); System.out.println("解析结果 = " + result.toString()); System.out.println("二维码格式类型 = " + result.getBarcodeFormat()); System.out.println("二维码文本内容 = " + result.getText()); } catch (Exception e) { e.printStackTrace(); } } }
public class BufferedImageLuminanceSource extends LuminanceSource { private final BufferedImage image; private final int left; private final int top; public BufferedImageLuminanceSource(BufferedImage image) { this(image, 0, 0, image.getWidth(), image.getHeight()); } public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) { super(width, height); int sourceWidth = image.getWidth(); int sourceHeight = image.getHeight(); if (left + width > sourceWidth || top + height > sourceHeight) { throw new IllegalArgumentException("Crop rectangle does not fit within image data."); } for (int y = top; y < top + height; y++) { for (int x = left; x < left + width; x++) { if ((image.getRGB(x, y) & 0xFF000000) == 0) { image.setRGB(x, y, 0xFFFFFFFF); // = white } } } this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY); this.image.getGraphics().drawImage(image, 0, 0, null); this.left = left; this.top = top; } @Override public byte[] getRow(int y, byte[] row) { if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); if (row == null || row.length < width) { row = new byte[width]; } image.getRaster().getDataElements(left, top + y, width, 1, row); return row; } @Override public byte[] getMatrix() { int width = getWidth(); int height = getHeight(); int area = width * height; byte[] matrix = new byte[area]; image.getRaster().getDataElements(left, top, width, height, matrix); return matrix; } @Override public boolean isCropSupported() { return true; } @Override public LuminanceSource crop(int left, int top, int width, int height) { return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height); } @Override public boolean isRotateSupported() { return true; } @Override public LuminanceSource rotateCounterClockwise() { int sourceWidth = image.getWidth(); int sourceHeight = image.getHeight(); AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth); BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g = rotatedImage.createGraphics(); g.drawImage(image, transform, null); g.dispose(); int width = getWidth(); return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width); } }
java生成二维码或条形码需要 zxing-*.jar 包的支持(密码:h8gk)