java生成二维码图片

 

1、POM文件引入

 

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

 

 

2、java代码编写,servlet或spring mvc 的Controller

 

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by user1 on 2015/8/12.
 */
@Controller
@RequestMapping(value = "/qrcode", produces = "application/json; charset=UTF-8")
public class QRCodeController {

    private static Logger logger = LoggerFactory.getLogger(QRCodeController.class);


    /**
     * 生成验证码图片
     * @param response
     * @throws java.io.IOException
     */
    @RequestMapping(value = "/qrcode", produces = "image/png")
    public void createQRCode(
            @RequestParam(value = "type")String type,
            HttpServletRequest request, HttpServletResponse response) throws IOException {

        //生成需要分享的二维码,也可以根据此参数生成其他的二维码,只要增加更多else if
        if ("test".equalsIgnoreCase(type)){

            //生成二维码图片的内容
            String qrCodeContent = "http://www.coolpeng.cn";

            //生成二维码图片
            encodeQRCode(response, qrCodeContent);

            logger.debug("qrCodeContent  {}", qrCodeContent);
        }

    }





    /**
     * 生成二维码图片并作为输出流输出到页面上
     * @param resp
     * @param content
     * @throws IOException
     */
    private void encodeQRCode(HttpServletResponse resp,String content) throws IOException {

        ServletOutputStream out = resp.getOutputStream();

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {

            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);

            //里面自己会把流close的
            MatrixToImageWriter.writeToStream(bitMatrix, "png", out);

        } catch (WriterException | IOException e ) {
            logger.error("",e);
        }
    }


}

 

posted on 2016-01-20 09:58  袜子破了  阅读(301)  评论(0编辑  收藏  举报