依赖
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.1</version> </dependency>
service
import com.google.zxing.*; 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 java.awt.image.BufferedImage; import java.io.IOException; import java.util.HashMap; @Service public class QRCodeService { public BufferedImage generateQRCode(String text, int width, int height) throws WriterException, IOException { QRCodeWriter qrCodeWriter = new QRCodeWriter(); // 设置二维码参数 HashMap<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); } }
controller
package boot.controller; import boot.service.QRCodeService; import com.google.zxing.WriterException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; @RestController public class QRCodeController { @Autowired private QRCodeService qrCodeService; @GetMapping(value = "/qrcode/{text}", produces = MediaType.IMAGE_PNG_VALUE) public byte[] getQRCode(@PathVariable("text") String text, @RequestParam(defaultValue = "200") int width, @RequestParam(defaultValue = "200") int height) throws IOException, WriterException { BufferedImage qrcodeImage = qrCodeService.generateQRCode(text, width, height); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(qrcodeImage, "PNG", outputStream); return outputStream.toByteArray(); } @PostMapping(value = "/qrcode2", produces = MediaType.IMAGE_PNG_VALUE) public byte[] getQRCode2(@RequestBody String text, @RequestParam(defaultValue = "200") int width, @RequestParam(defaultValue = "200") int height) throws IOException, WriterException { BufferedImage qrcodeImage = qrCodeService.generateQRCode(text, width, height); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(qrcodeImage, "PNG", outputStream); return outputStream.toByteArray(); } }
测试
标签:google,text,zxing,二维码,outputStream,import,生成,com From: https://www.cnblogs.com/ixtao/p/17441771.html