准备工作
- 导入core的jar包或者加入依赖在maven工程中
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.0</version></dependency>
- 理解io流相关知识
- 理解java面向对象
- 理解集合的使用
- 理解ImageIO流输出图片
代码实现
publicclassTestMain{publicstaticvoidgetQRCode()throws Exception{
QRCodeWriter qrCodeWriter=newQRCodeWriter();
String contents="晖哥真帅!";
BarcodeFormat qrCodeType= BarcodeFormat.QR_CODE;
HashMap map=newHashMap();
map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
map.put(EncodeHintType.MARGIN,2);
BitMatrix bitMatrix= qrCodeWriter.encode(contents,qrCodeType,600,600, map);
BufferedImage bufferedImage=newBufferedImage(bitMatrix.getWidth(),bitMatrix.getHeight(),BufferedImage.TYPE_INT_RGB);int getBlack= Color.black.getRGB();int getWrite=Color.white.getRGB();for(int x=0; x<bitMatrix.getWidth(); x++){for(int y=0; y<bitMatrix.getHeight(); y++){
bufferedImage.setRGB(x, y, bitMatrix.get(x, y)? getBlack: getWrite);}}
ImageIO.write(bufferedImage,"jpg",newFile("src/qrcode/QRCode.jpg"));}publicstaticvoidmain(String[] args){try{
TestMain.getQRCode();}catch(Exception e){
e.printStackTrace();}}}