public class Test { public static void main(String[] args) throws WriterException, IOException { String content = "wetsdfqeojsdfasdf" ;// 內容 int width = 400; // 圖像寬度 int height = 400; // 圖像高度 // 參數設置 Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType. CHARACTER_SET, "UTF-8" ); // 內容編碼 //容錯 hints.put(EncodeHintType. ERROR_CORRECTION,ErrorCorrectionLevel.L); //矩陣形狀 - 長方形 - 正方形 hints.put(EncodeHintType. DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_NONE ); //矩陣邊緣 hints.put(EncodeHintType. MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat. QR_CODE, width, height, hints); // 生成矩陣 //顏色 // MatrixToImageConfig config = new MatrixToImageConfig(Integer.MAX_VALUE -5548, MatrixToImageConfig.WHITE ); writeToFile(bitMatrix, "png" , new File("d://zxing.png"), "d://3.png"); // MatrixToImageWriter. writeToFile(bitMatrix, "png ", new File("d://zng.png") ); /*MemoryCacheImageOutputStream outputStream = new MemoryCacheImageOutputStream(null); BufferedImage im = new BufferedImage(0, 0, BufferedImage.TYPE_INT_RGB); ImageIO.write( im, "png ", new File("d://img.png"));*/ System. out.println( "完成生成"); } /** * * @param matrix 二維碼矩陣相關 * @param format 二維碼圖片格式 * @param file 二維碼圖片文件 * @param logoPath logo路徑 * @throws IOException */ public static void writeToFile(BitMatrix matrix,String format,File file,String logoPath) throws IOException { BufferedImage barCode = toBufferedImage(matrix); //載入logo BufferedImage logo = ImageIO. read(new File(logoPath)); //System.out.println(String.format("barcode width :%d logo: %d", barCode.getWidth(),logo.getWidth())); int nestX = (barCode.getWidth()-logo.getWidth())/2; int nestY = (barCode.getHeight()-logo.getHeight() )/2; System. out.println(nestX); Graphics2D gs = barCode.createGraphics(); gs.drawImage(logo, nestX, nestY, null); gs.dispose(); logo.flush(); if(!ImageIO.write(barCode, format, file)){ throw new IOException( "Could not write an image of format " + format + " to " + file); } } public static BufferedImage toBufferedImage(BitMatrix matrix){ int width = matrix.getWidth(); int height = matrix.getHeight(); int white = 0xFF000000; int black = 0xFFFFFFFF; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for(int x=0;x<width;x++){ for( int y=0;y<height;y++){ image.setRGB(x, y, matrix.get(x, y) ? white: black ); } } return image; } }