1 changed files with 55 additions and 0 deletions
@ -0,0 +1,55 @@ |
|||
package com.dreamchaser.depository_manage.utils; |
|||
|
|||
import cn.hutool.core.codec.Base64; |
|||
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.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; |
|||
|
|||
/* |
|||
** 二维码生成 |
|||
*/ |
|||
public class CreateQrCodeUtil { |
|||
public String createQrCode(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.encode(os.toByteArray())); |
|||
return resultImage; |
|||
} catch (Exception e) { |
|||
e.printStackTrace(); |
|||
} finally { |
|||
if (stream != null) { |
|||
stream.flush(); |
|||
stream.close(); |
|||
} |
|||
} |
|||
} |
|||
return null; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue