- 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;
- }
- }
来源: https://www.oschina.net/code/snippet_1992570_58665