java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java生成二维码

Java实现生成二维码展示到浏览器的示例代码

作者:夜空下的星

这篇文章主要介绍了Java实现生成二维码展示到浏览器的示例代码,要实现在浏览器展示二维码,那么首先需要html文件,通过Java生成二维码的工具类,在controller层调用接口,就可以实现在浏览器上展示二维码,需要的朋友可以参考下

要实现在浏览器展示二维码,那么首先需要html文件,通过Java生成二维码的工具类,在controller层调用接口,就可以实现在浏览器上展示二维码。

html文件内容如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:http="http://www.w3.org/1999/xhtml"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>二维码</title>
<script th:src="@{../js/jquery-3.1.1.js}"></script>
<style type="text/css">
	#qrcode-mask{
		margin-left: 40px;
		margin-top: 30px;
	}
	#code-panel{
		width: 280px;
		height: 320px;
		border: 1px solid #e1e1e1;
		margin: 0 auto;
		margin-top: 30px;
		background-color: rgba(255,215,255,0.25);
		box-shadow: -4px -4px 6px rgba(0,0,0,0.35) inset;
	}
	/*rgba(25,252,205,0.15);*/
	#desc{
		color: #717375;
		font-size: 14px;
		text-align: center;
	}
</style>
 <script type="text/javascript">
    	onload=function(){
    		$.ajax({
    			type: 'POST',
    			url: '/qrcode/img',
    			dataType: 'json',
    			data: '',
    			success:function (result) {
    	        	if (result.code == 1){
    	        		$("#qrcode").attr('src','data:image/png;base64,'+result.data.img);
    	        	}else{
    	        		alert(result.info);
    	        	}
    	        },
    	        error:function (result) {
    	        	alert("获取失败");
    	        }
    	    });
    	}
 </script>
</head>
<body>
	<div id="code-panel">
		<div id="qrcode-mask">
			<img id="qrcode" alt="" src="">
		</div>
		<div id="desc">
			扫描并关注<br>
			微信公众平台
		</div>
	</div>
</body>
</html>

接着在Controller层实现一个接口,代码如下:

import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.suntree.commons.ApiResult;
import com.suntree.utils.QRCodeUtil;
@SpringBootApplication
@RestController
@RequestMapping("/qrcode")
public class QRCodeContoller {
	/**
	 * 获取二维码图片
	 * @return
	 */
	@PostMapping("/img")
	public ApiResult getQRCodeImage() {
		ApiResult result=new ApiResult();
		Map<String,Object> img=new HashMap<>();
		String content="https://guangz-myblog.oss-cn-shenzhen.aliyuncs.com/private/user/%E5%88%98%E5%85%89%E5%AE%97/ff52da04-009d-49b4-9601-936c33bb0673.png";
		String imgPath="https://guangz-myblog.oss-cn-shenzhen.aliyuncs.com/private/user/%E5%88%98%E5%85%89%E5%AE%97/ff52da04-009d-49b4-9601-936c33bb0673.png";
		String base64=QRCodeUtil.getImageToBase64(content, imgPath, true);
		img.put("img", base64);
		return result.success(img);
	}
}

这个获取的是二维码图片的base64;

再接下来就是实现生成二维码的工具类,代码如下:

import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
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 sun.misc.BASE64Encoder;
public class QRCodeUtil {
	private static final String CHARSET = "utf-8";
	private static final String FORMAT_NAME = "PNG";
	// 二维码尺寸
	private static final int QRCODE_SIZE = 200;
	// LOGO宽度
	private static final int WIDTH = 60;
	// LOGO高度
	private static final int HEIGHT = 60;
	/**
	 * 创建图片
	 * @param content
	 * @param imgPath
	 * @param needCompress
	 * @return
	 * @throws Exception
	 */
	private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
		Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
		hints.put(EncodeHintType.MARGIN, 1);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
				hints);
		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);
			}
		}
		if (imgPath == null || "".equals(imgPath)) {
			return image;
		}
		// 插入图片
		QRCodeUtil.insertImage(image, imgPath, needCompress);
		return image;
	}
	/**
	 * 插入图片
	 * @param source
	 * @param imgPath
	 * @param needCompress
	 * @throws Exception
	 */
	private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
		File file = new File(imgPath);
		if (!file.exists()) {
			System.err.println("" + imgPath + "   该文件不存在!");
			return;
		}
		Image src = ImageIO.read(file);
		int width = src.getWidth(null);
		int height = src.getHeight(null);
		if (needCompress) { // 压缩LOGO
			if (width > WIDTH) {
				width = WIDTH;
			}
			if (height > HEIGHT) {
				height = HEIGHT;
			}
			Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			//Graphics g = tag.getGraphics();
			Graphics2D g2 = (Graphics2D) tag.getGraphics();
			g2.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g2.dispose();
			src = image;
		}
		// 插入LOGO
		Graphics2D graph = source.createGraphics();
		int x = (QRCODE_SIZE - width) / 2;
		int y = (QRCODE_SIZE - height) / 2;
		graph.drawImage(src, x, y, width, height, null);
		Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
		graph.setStroke(new BasicStroke(3f));
		graph.draw(shape);
		graph.dispose();
	}
	/**
	 * 
	 * 生成二维码并放入本地
	 * @param content
	 * @param imgPath
	 * @param destPath
	 * @param needCompress
	 * @throws Exception
	 */
	public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
		mkdirs(destPath);
		ImageIO.write(image, FORMAT_NAME, new File(destPath));
	}
	public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
		return image;
	}
	public static void mkdirs(String destPath) {
		File file = new File(destPath);
		// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
	}
	public static void encode(String content, String imgPath, String destPath) throws Exception {
		QRCodeUtil.encode(content, imgPath, destPath, false);
	}
	public static void encode(String content, String destPath) throws Exception {
		QRCodeUtil.encode(content, null, destPath, false);
	}
	public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
			throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
		ImageIO.write(image, FORMAT_NAME, output);
	}
	public static void encode(String content, OutputStream output) throws Exception {
		QRCodeUtil.encode(content, null, output, false);
	}
	public static String decode(File file) throws Exception {
		BufferedImage image;
		image = ImageIO.read(file);
		if (image == null) {
			return null;
		}
		BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Result result;
		Map<DecodeHintType,Object> hints = new HashMap<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
		result = new MultiFormatReader().decode(bitmap, hints);
		String resultStr = result.getText();
		return resultStr;
	}
	/**
	 * 生成二维码图片转base64
	 * 
	 * @param content
	 * @param imgPath
	 * @param needCompress
	 * @return
	 */
	public static String getImageToBase64(String content, String imgPath, boolean needCompress) {
		ByteArrayOutputStream out=null;
		try {
			BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
			out = new ByteArrayOutputStream();
			ImageIO.write(image,"png",out);
			byte[] b = out.toByteArray();
			BASE64Encoder encoder = new BASE64Encoder();
	        return encoder.encode(b);//生成base64编码 
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(out!=null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}

最后实现WebMvcConfigurer接口,这样就可以在浏览器上展示二维码了。

大家可以自己去试试,望大家多多支持!

到此这篇关于Java实现生成二维码展示到浏览器的示例代码的文章就介绍到这了,更多相关Java生成二维码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文