Java 中生成二维码
2022-11-06 20:30:09
我们在做会员系统或类似需求时,经常需要生成二维码给商家扫描,Java 中使用 zxing 库可以方便的生成二维码。
### 添加依赖
```
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.1</version>
</dependency>
```
### 示例代码
```
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ImageController {
@GetMapping("/qrcode")
public void qrcode(HttpServletResponse response) {
try {
String filePath = "./";
String fileName = "test.png";
String content = "hello";
int width = 200; // 图像宽度
int height = 200; // 图像高度
String format = "png"; // 图像类型
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// Path path = FileSystems.getDefault().getPath(filePath, fileName);
// MatrixToImageWriter.writeToPath(bitMatrix, format, path); // 输出图像到文件中
// 浏览器直接显示
MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```