二维码生成器

一、介绍:本文为二维码不在服务器生成图片直接输出在客户端;访问方式可以为img标签中src为“aa/getQCode?text=”;

二、二维码生成器分为两种,小日本的qCord导入谷歌zxing的jar包;其中zxing的maven依赖是:

            <dependency>
		    <groupId>com.google.zxing</groupId>
		    <artifactId>core</artifactId>
		    <version>3.0.0</version>
	    </dependency>
	    <dependency>
		    <groupId>com.google.zxing</groupId>
		    <artifactId>javase</artifactId>
		    <version>3.0.0</version>   
	    </dependency>

三、代码部分:

        @RequestMapping(value = "getQRCoder")
	@ResponseBody
	public void getQRCoder(HttpServletResponse response,String text){
		//设置页面不缓存
		response.setHeader("Pragma","No-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);

		int width2 = 233; 
		int height2 = 233; 
		//二维码的图片格式
		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); 
		//内容所使用编码 
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, width2, height2, hints);
			bitMatrix = deleteWhite(bitMatrix);
			int width = bitMatrix.getWidth(); 
			int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); //二维码图片为黑白两色
				} 
			}
			ImageIO.write(image,"gif",response.getOutputStream());
			//生成二维码 
			//File outputFile = new File("d:"+File.separator+"new.gif"); 
			//MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值