发布网友 发布时间:2022-04-25 14:41
共2个回答
热心网友 时间:2023-10-09 14:57
java生成二维码如何去除白边
新代码:(注意点查看图片截图的标注) Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.MARGIN
热心网友 时间:2023-10-09 14:58
新代码:(注意点查看图片截图的标注)
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix = new QRCodeWriter().encode("生成二维码的内容",
BarcodeFormat.QR_CODE, 256, 256,hints);
//1.1去白边
int[] rec = bitMatrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (bitMatrix.get(i + rec[0], j + rec[1])) {
resMatrix.set(i, j);
}
}
}
//2
int width = resMatrix.getWidth();
int height = resMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, resMatrix.get(x, y) == true ?
Color.BLACK.getRGB():Color.WHITE.getRGB());
}
}
//3
ImageIO.write(image,"png", new File("生成二维码保存的路径"));