简单二维码制作JAVA实现
前几天闲来无事,做了个二维码玩玩,刚开始我还以为是要自己写一些原理代码出来,查了下资料原来还是可以用别人写好的jar包来实现,网上有两种jar包,我这里使用的是谷歌的zxing包。我总结了有四个步骤:
//先设置好保存EncodeHintType枚举类型的Map集合,在通过MultiFormatWritert.encode()函数生成二进制矩阵BitMatrix int width=400; int height=400; Map<EncodeHintType,Object> hints=new HashMap<EncodeHintType,Object>(); hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");//设置编码格式 hints.put(EncdoeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.L); //设置容错级别L,最好设置为高等级H hints.put(EncodeHintType.DATA_MATRIX_SHAPE,SymbolShapeHint.FORCE_NONE); hints.put(EncodeHintType.MARGIN,1);//设置外边距 BitMatrix bitmatrix=new MultiFormatWriter().encode("http://www.baidu.com",BarcodeFormat.QR_CODE,width,height,hints); //生成二进制矩阵 //再根据获得的二进制矩阵,遍历矩阵的每个坐标点获得有数据的BufferedImage图像缓存对象。 int width=matrix.getWidth(); int height=martix.getHeight(); BufferedImage bufferedimage=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,matrix.get(x,y)?red:kaqi); } return bufferedimage; } //如果需要logo,则在之前的图片缓存区的画笔中把logo的缓存写入。 BufferedImage logo=ImageIo.read(new File(logoPath)); int x=(bufferedimage.getWidth()-logo.getWidth())/2; int y=(bufferedimage.getHeight()-logo.getHeight())/2; Graphics2D gs=bufferedimage.createGraphics(); gs.drawImage(logo,x,y,null); gs.dispose(); logo.flush(); if(!ImageIo.write(bufferedimage,format,file)){ throw new IOException("无法写入图片"); }
颜色,大小,logo和字符串都可以自由设置,是不是很简单呢。