我正在使用 ZXING 库在 JAVA 中创建 QR 码生成器程序。程序是
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class QR_Gen {
private static final String QR_CODE_IMAGE_PATH = "./MyCode.png";
private static void generateQRCodeImage(String text, int width, int
height, String filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text,
BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
public static void main(String[] args) {
try {
generateQRCodeImage("This is my first QR Code", 350, 350, QR_CODE_IMAGE_PATH);
System.out.println("QR Code generated successfully");
} catch (WriterException e) {
System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
} catch (IOException e) {
System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
}
}
}
编译此程序时,我收到类型不匹配错误,
Type mismatch: cannot convert from ByteMatrix to BitMatrix
在这一行
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
请帮忙!!!
最佳答案
根据javadoc here和源代码here ,QRCodeWriter.encode
方法返回 BitMatrix
,不是ByteMatrix
。因此,该编译错误不应发生。
除非......
...您正在使用 com.google.zxing
的某个版本1与这些 javadoc 不兼容的库。检查您从哪里获取 zxing JAR 文件。
尽管进行了搜索,但我仍无法找到具有这种不兼容性的版本。但是:
我注意到官方库已在 GitHub 上多次 fork ,其中任何一个都可能是不兼容的根源。
我找到了this这显然是一个 fork ,并且显然已经进行了调整
encode
。然而,这样做的人至少有良好的判断力来更改包名称!
我不知道这是否相关,但似乎在此 API 的 C# 版本中,QRCodeWriter.encode
方法确实返回 ByteMatrix
;请参阅here为证据。也许您偶然发现了某人试图“修复”Java API 以匹配 C# API 的错误尝试。
关于java - 类型不匹配 : cannot convert from ByteMatrix to BitMatrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51763384/