2
我現在有這個類,它創建一個帶有QR碼的圖像,它的效果很好。 但是,當我使用這個類來創建另一個QR碼,通過餵它一個新的字符串第一個QR碼被繪... 請幫助! 有沒有辦法初始化Graphics2d或BufferedImage?我是havig生成QR碼的麻煩動態
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();
}
}
}
我很新的Java,我應該如何改變我的代碼? –
刪除靜態字段並在該方法內移動相同的兩行。 String filePath =「QR _」+ myText +「。jpg」; 文件myFile =新文件(filePath); \ n if(myFile.exists()){System.out.println(「File already exists」); System.exit(1); }這將確保文件總是在行後面新創建。添加\ n ImageIO.write(image,fileType,myFile); \ n – hemal
太棒了!我很感激 ;-) –