代码
import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.io.BufferedOutputStream; import java.io.File; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Hashtable; import java.util.Random; /** * @Title: QRCodeUtil * @Description: 二维码工具包 * @author: Nathan * @date: 2018/5/9 * @version: V1.0 */ public class QRCodeUtil { private static final String CHARSET = "utf-8"; public static final String FORMAT_NAME = "JPG"; private static final int defaultSize = 640; private static final int defaultLogonSize = 64; private static Logger logger = LoggerFactory.getLogger(utils.QRCodeUtil.class); public QRCodeUtil() { } private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception { Image src = null; if (imgPath != null) { File file = new File(imgPath); if (file.exists()) { src = ImageIO.read(new File(imgPath)); } else { logger.error("" + imgPath + " 该文件不存在!"); } } return createImage(content, src, needCompress, 640, 640, 64, 64); } private static BufferedImage createImage(String content, Image src, boolean needCompress, int iW, int iH, int logonWidth, int logonHeight) throws Exception { Hashtable<EncodeHintType, Object> hints = new Hashtable(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = (new MultiFormatWriter()).encode(content, BarcodeFormat.QR_CODE, iW, iH, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, 1); for(int x = 0; x < width; ++x) { for(int y = 0; y < height; ++y) { image.setRGB(x, y, bitMatrix.get(x, y) ? -16777216 : -1); } } if (src == null) { return image; } else { insertImage(image, src, needCompress, iW, iH, logonWidth, logonHeight); return image; } } private static void insertImage(BufferedImage source, Image src, boolean needCompress, int iW, int iH, int logonWidth, int logonHeight) throws Exception { if (src != null) { int width = src.getWidth((ImageObserver)null); int height = src.getHeight((ImageObserver)null); if (needCompress) { if (width > logonWidth) { width = logonWidth; } if (height > logonHeight) { height = logonHeight; } Image image = src.getScaledInstance(width, height, 4); BufferedImage tag = new BufferedImage(width, height, 1); Graphics g = tag.getGraphics(); g.drawImage(image, 0, 0, (ImageObserver)null); g.dispose(); src = image; } Graphics2D graph = source.createGraphics(); int x = (iW - width) / 2; int y = (iH - height) / 2; graph.drawImage(src, x, y, width, height, (ImageObserver)null); Shape shape = new RoundRectangle2D.Float((float)x, (float)y, (float)width, (float)width, 15.0F, 15.0F); graph.setStroke(new BasicStroke(3.0F)); graph.draw(shape); graph.dispose(); } } public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception { BufferedImage image = createImage(content, imgPath, needCompress); mkdirs(destPath); String file = (new Random()).nextInt(99999999) + ".jpg"; ImageIO.write(image, "JPG", new File(destPath + "/" + file)); } public static void mkdirs(String destPath) { File file = new File(destPath); if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } } public static void encode(String content, String imgPath, String destPath) throws Exception { encode(content, imgPath, destPath, false); } public static void encode(String content, String destPath, boolean needCompress) throws Exception { encode(content, (String)null, destPath, needCompress); } public static void encode(String content, String destPath) throws Exception { encode(content, (String)null, destPath, false); } public static int getActualSize(Integer size) { if (size == null || size <= 0) { size = 640; } if (size < 16) { size = 16; } if (size > 3000) { size = 3000; } return size; } public static void encode(String content, Image src, OutputStream output, boolean needCompress, Integer size) throws Exception { size = getActualSize(size); BufferedImage image = createImage(content, src, needCompress, size, size, 64, 64); ImageIO.write(image, "JPG", output); } public static void encode(String content, OutputStream output, Integer size) throws Exception { encode(content, (Image)null, output, false, size); } public static String decode(File file) throws Exception { BufferedImage image = ImageIO.read(file); if (image == null) { return null; } else { BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable<DecodeHintType, String> hints = new Hashtable(); hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); Result result = (new MultiFormatReader()).decode(bitmap, hints); String resultStr = result.getText(); return resultStr; } } public static String decode(String path) throws Exception { return decode(new File(path)); } public static int getLogoSize(Integer size) { size = getActualSize(size); int i = size / 10; if (i <= 0) { i = 1; } return i; } /** * 生成二维码 * @param response * @param qrValue 二维码值 * @param size 二维码的大小 * @param codeName 二维码图片名称 * @param isOpen 区分下载/打开 1下载,其他打开 * @throws Exception */ public static void createQrcodeImage(HttpServletResponse response, String qrValue, Integer size , String codeName, String isOpen) throws Exception { if ((qrValue != null) && (qrValue.length() > 0)) { Image src = null; Resource resource = new ClassPathResource("qrcode/logo.png"); if (resource.exists()) { src = ImageIO.read(resource.getInputStream()); src = src.getScaledInstance(QRCodeUtil.getLogoSize(size), QRCodeUtil.getLogoSize(size), Image.SCALE_DEFAULT); } try { qrValue = URLDecoder.decode(qrValue, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); logger.error("URLDecoder", e); } response.reset(); if("1".equals(isOpen)){ response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(codeName,"UTF-8") ); }else{ response.setHeader("content-disposition", "inline;filename="+URLEncoder.encode(codeName,"UTF-8") ); } response.setContentType("image/" + QRCodeUtil.FORMAT_NAME); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); QRCodeUtil.encode(qrValue, src, toClient, false, size); } } }
maven依赖
<!--生成二维码依赖包--> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.2</version> </dependency>