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

I'm havig trouble generating QR codes dynamicaly

我现在有这个 class,它创建了一个带有二维码的图像,效果很好。 但是,当我使用此 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 或图像文件的声明有问题。

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

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

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

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

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