java生成二维码输出到并前端
直接以图片形式返回给前端
public class QrCodeUtil {
private static final int BLACK = -16777216;
private static final int WHITE = -1;
public QrCodeUtil() {
}
public static BitMatrix createQrCode(String path) {
try {
Map<EncodeHintType, String> hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = (new MultiFormatWriter()).encode(path, BarcodeFormat.QR_CODE, 400, 400, hints);
return bitMatrix;
} catch (Exception var3) {
var3.printStackTrace();
return null;
}
}
static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, 1);
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
image.setRGB(x, y, matrix.get(x, y) ? -16777216 : -1);
}
}
return image;
}
// 设置响应流信息
response.setContentType("image/jpg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream stream = response.getOutputStream();
//获取一个二维码图片
BitMatrix bitMatrix = QrCodeUtil.createQrCode(path);
//以图片的形式输出到前端
ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , imageOut);
拼装图片字节流返回给前端
// 设置响应流信息
response.setContentType("image/jpg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream stream = response.getOutputStream();
//获取一个二维码图片
BitMatrix bitMatrix = QrCodeUtil.createQrCode(path);
ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
//以流的形式输出到前端
ByteArrayInputStream imageIn = new ByteArrayInputStream(imageOut.toByteArray());
BufferedImage bImage = ImageIO.read(imageIn);
ByteArrayOutputStream bs =new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg" , bs);
byte[] bytes = bs.toByteArray();
Base64.Encoder encoder = Base64.getEncoder();
return "data:image/jpg;base64,"+ encoder.encodeToString(bytes);
该博客介绍如何在Java中生成二维码,并将其以图片形式的字节流直接返回到前端进行展示。

6486

被折叠的 条评论
为什么被折叠?



