java代码生成二维码

java代码生成二维码一般步骤

常用的是Google的Zxing来生成二维码,生成的一般步骤如下:

一、下载zxing-core的jar包:

 

二、需要创建一个MatrixToImageWriter类,此类google的源码中提供了,为了使用方便,下面是类中的代码,可以直接复制来使用:

	private static final int BLACK = 0xFF000000;
	   private static final int WHITE = 0xFFFFFFFF;
	 
	   private MatrixToImageWriter() {}
	 
	   
	   public static BufferedImage toBufferedImage(BitMatrix matrix) {
	     int width = matrix.getWidth();
	     int height = matrix.getHeight();
	     BufferedImage image = 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) ? BLACK : WHITE);
	       }
	     }
	     return image;
	   }
	 
	   
	   public static void writeToFile(BitMatrix matrix, String format, File file)
	       throws IOException {
	     BufferedImage image = toBufferedImage(matrix);
	     if (!ImageIO.write(image, format, file)) {
	       throw new IOException("Could not write an image of format " + format + " to " + file);
	     }
	   }
	 
	   
	   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);
	     }
	   }

  三、创建一个启动类,用来生成二维码:(注意:二维码访问的url地址需要注意,如果书写成www格式的,需要浏览器扫一扫,同样的地址写成http格式的可以用任何扫码器扫都可以

	
	public static void main(String[] args) {
		try {
             //二维码访问的网址地址1:www.baidu.com或者http://baidu.com
		     String content = "http://baidu.com";
		     //二维码图片保存的路径
		     String path = "D:/test";
		     MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		     Map hints = new HashMap();
		     hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		     BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 100, 100,hints);
		     File file1 = new File(path,"百度首页.jpg");
		     MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
		     
		 } catch (Exception e) {
		     e.printStackTrace();
		 }
	}

  四、经过亲自测试可以生成二维码,需要特别注意的是:

  二维码访问的url地址书写,一般情况下都是写成http格式的;

posted @ 2017-09-22 16:07  lsyBlog  阅读(944)  评论(0编辑  收藏  举报