Java生成二维码

简介:

工作中我们经常会用到二维码生成工具,这里就介绍一个项目中用到的工具

pom:

<!--生成二维码-->
    <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>core</artifactId>
      <version>3.2.0</version>
    </dependency>

utils:

package com.pk.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码工具类
 * 
 */
public class QRCodeUtil {

	private static final String CHARSET = "utf-8";
	private static final String FORMAT_NAME = "PNG";

	private static BufferedImage createImage(String content, int qrcode_size) throws Exception {
		qrcode_size += 13;
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrcode_size, qrcode_size, hints);
		int[] rec = bitMatrix.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 (bitMatrix.get(i + rec[0], j + rec[1])) { 
		             resMatrix.set(i, j); 
		        } 
		    }  
		}  
		int width = resMatrix.getWidth();
		int height = resMatrix.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, resMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
			}
		}
		return image;
	}

	/**
	 * 生成二维码
	 * 
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param destPath
	 *            存放目录
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static ByteArrayOutputStream encode(String content,int qrcode_size) throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content,qrcode_size);
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(image,FORMAT_NAME,out);
//		String file = new Random().nextInt(99999999)+".jpg";
//		ImageIO.write(image, FORMAT_NAME, new File("d:/"+file));
		return out;
	}


	public static void main(String[] args) throws Exception {
//		ByteArrayOutputStream out = QRCodeUtil.encode(text,118);
	}
}

Controller:

/**
     * 二维码生成
     * @return
     */
    @RequestMapping(value = "/qr4wap")
    @ResponseBody
    public void qr4wap(HttpServletResponse response){
        try (OutputStream out = response.getOutputStream()) {
            ByteArrayOutputStream byteArrayOutputStream = QRCodeUtil.encode("二维码内容", 150);
            response.setContentLength(byteArrayOutputStream.size());
            out.write(byteArrayOutputStream.toByteArray());
        } catch (Exception e) {
            logger.debug("生成二维码: {}", e.getMessage());
        }
    }

jsp:

生成二维码:<img src="<%=request.getContextPath() %>/qr4wap" >

好了 项目启动搞定

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值