gpt4 book ai didi

java - 我在动态生成二维码时遇到问题

转载 作者:行者123 更新时间:2023-11-30 10:57:10 25 4
gpt4 key购买 nike

我现在有这个类(class),它创建了一个带有二维码的图像,效果很好。但是,当我使用此类通过为其提供新字符串来创建另一个 QR 码时,第一个 QR 码被绘制......请帮忙!有没有办法初始化 Graphics2d 或 BufferedImage?

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCodeGenerator {

int size = 300;
String fileType = "jpg";

static String filePath = "QR.jpg";
static File myFile = new File(filePath);
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = new BitMatrix(300, 300);
BufferedImage image;
Graphics2D graphics;

QRCodeGenerator(String myText) {

try {
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
byteMatrix = qrCodeWriter.encode(myText, BarcodeFormat.QR_CODE,
size, size, hintMap);
int width = byteMatrix.getWidth();
image = new BufferedImage(width, width, BufferedImage.TYPE_INT_RGB);
image.createGraphics();

graphics = (Graphics2D) image.getGraphics();
graphics.setColor(ColorsClass.colorBackground);
graphics.fillRect(0, 0, width, width);
graphics.setColor(ColorsClass.colorForeground);

for (int i = 0; i < width; i++) {
for (int j = 0; j < width; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
ImageIO.write(image, fileType, myFile);
System.out.println(myText);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

这似乎是您需要写入的字段 myFile 或图像文件的声明问题。

如以下链接所述。每次都必须明确关闭和打开图像文件

您也可以尝试在每次想要创建二维图像时创建一个不同名称的新文件,如“QR_1.jpg”、“QR_2.jpg”,从而减少覆盖和丢失以前数据的可能性。

http://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html

使用支持给定格式的任意 ImageWriter 将图像写入 ImageOutputStream。图像从当前流指针开始写入 ImageOutputStream,覆盖从该点向前的现有流数据(如果存在)。

写操作完成后,此方法不会关闭提供的 ImageOutputStream;如果需要,调用者有责任关闭流。

关于java - 我在动态生成二维码时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32739477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com