如何用Java编写出一个二维码
前几天在网上看见一个用Java编写二维码的教学视频,今天来简单地来分享下如何用Java来编写二维码。
public class createQRCode {
public static void main(String[] args) {
int width = 300;
int height = 300;
String format="png";
String content = "这是一个Java编写的二维码";
//定义二维码参数
HashMap ewm = new HashMap();
ewm.put(EncodeHintType.CHARACTER_SET,"utf-8");
ewm.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);
ewm.put(EncodeHintType.MARGIN, 5);
try {
//生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,ewm);
Path file = new File("D:/img.png").toPath();
try {
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
需要注意的问题:在第一次编写二维码时,需要手动在Java工程中导入一个zxing3.3.3.jar的文件,否则代码无法编译执行。
该二维码是通过QRCode 码生成 。 QRCode 码详细解答