1 import com.google.zxing.BarcodeFormat;
2 import com.google.zxing.WriterException;
3 import com.google.zxing.client.j2se.MatrixToImageWriter;
4 import com.google.zxing.common.BitMatrix;
5 import com.google.zxing.qrcode.QRCodeWriter;
6
7 import javax.servlet.ServletOutputStream;
8 import javax.servlet.http.HttpServletResponse;
9 import java.io.File;
10
11 public class CreateQrcode {
12
13
14 /**
15 * 生成二维码方法
16 *
17 * @param url 二维码表示数据
18 * @param resp response对象
19 * @throws Exception 抛出异常
20 */
21 public void getQrcode(String url, HttpServletResponse resp) throws Exception {
22 ServletOutputStream stream = null;
23 try {
24
25 String format = "jpg";// 二维码的图片格式
26 File outputFile = new File("d:" + File.separator + "new.jpg");
27 stream = resp.getOutputStream();
28 QRCodeWriter qrCodeWriter = new QRCodeWriter();
29 BitMatrix bm = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, 300, 300);
30 MatrixToImageWriter.writeToStream(bm, "png", stream);
31 MatrixToImageWriter.writeToFile(bm, format, outputFile);
32 } catch (WriterException e) {
33 e.getStackTrace();
34 } finally {
35 if (stream != null) {
36 stream.flush();
37 stream.close();
38 }
39 }
40 }
41 }