JavaはQRコードを作成し、base64を返します

イルカエルフhttps : //mgo.whhtjl.com

ここでバックエンドに使用するSpringBootおよびMavenプロジェクトのコードは次のとおりです。

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

サービス層を作成する

package com.ltf.service;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;  
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

@Service
public class QRCodeService {

	public String crateQRCode(String content, int width, int height) throws IOException {

		String resultImage = "";
		if (!StringUtils.isEmpty(content)) {
			ServletOutputStream stream = null;
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			@SuppressWarnings("rawtypes")
			HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 指定二维码的纠错等级为中级
			hints.put(EncodeHintType.MARGIN, 2); // 设置图片的边距
			try {
				QRCodeWriter writer = new QRCodeWriter();
				BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
				BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
				ImageIO.write(bufferedImage, "png", os);
				/**
				 * 原生转码前面没有 data:image/png;base64 这些字段,返回给前端是无法被解析,可以让前端加,也可以在下面加上
				 */
				resultImage = new String("data:image/png;base64," + Base64.encodeBase64String(os.toByteArray()));
				return resultImage;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (stream != null) {
					stream.flush();
					stream.close();
				}
			}
		}
		return null;
	}

}

コントローラー層を作成する

package com.ltf.controller;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.ltf.entity.User;
import com.ltf.service.QRCodeService;
import com.ltf.utils.SingletonLoginUtils;

@RestController
@RequestMapping("/qrcode")
public class QRCodeController extends BaseController{

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

	@Autowired
	QRCodeService qrCodeService;

	/**
	 * 获得课程二维码
	 * @param request
	 * @param courseName
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(path="/getCourseQRCode", method=RequestMethod.GET)
	@ResponseBody
	public JSONObject getCourseQRCode(HttpServletRequest request,@RequestParam("courseId") String courseId) {
		try {
			User user=SingletonLoginUtils.getLoginUser(request);
			if(user!=null){
				if(courseId!=null&&!"".equals(courseId.trim())&&Integer.parseInt(courseId)>0){
					String codeUrl = qrCodeService.crateQRCode(courseId,200,200);
					return this.formatJSON(200, codeUrl, null);
				}else{
					return this.formatJSON(500, "抱歉,课程名称获取失败!", null);
				}
			}else{
				return this.formatJSON(500, "抱歉,登录状态已失效,请重新登录!", null);
			}
		} catch (Exception e) {
			logger.error("QRCodeController.getCourseQRCode()----error", e);
			return this.formatJSON(500, "抱歉,获得课程二维码时出现异常!", null);
		}
	}

}

 

おすすめ

転載: blog.csdn.net/qq_35393693/article/details/107387678