關於用Java實現二維碼的生成


         昨天晚上看了一個視頻講的是web端把名片搞成二維碼的形式,覺得挺有意思的,不過我還是初學,所以就沒在網頁端實現,寫了命令行程序.

雖然看着程序很短,不過寫的過程中還是出了問題, 最致命的就是

Graphics2D.clearRect(0,0,235,235);
Graphics2D.setColor(Color.BLACK); 
這兩句代碼順序搞反,導致生成的二維碼異常,不能夠被讀取其中的信息. 當時檢查了好久都沒看出問題所在,其實現在來看先設置顏色再clean不就相當於沒設置顏色嗎,
所以以后一定要小心仔細,爭取少犯這種低級錯誤

 
package com.fantasyado.qrcoder;
import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Main
{


public static void main(String[] args)
{
// write your code here
String content="";
Scanner sc=new Scanner(System.in);
System.out.println("input your information,and ends with ok");
while(! content.endsWith("ok")){
content=content+"\n";
content=content.concat(sc.next());
}

content=content.substring(1,content.length()-2);
// content=content.replaceAll("ok","");

System.out.println("input your filename ends with EnterKey");
String filename=sc.next();
String filepath="D:\\"+filename+".png";
new Main().drawQRCODE(content, filepath);
System.out.println("draw QR_code successfullly!");
System.out.println(content);

}
public void drawQRCODE(String content,String filepath){
try {
Qrcode qrcode=new Qrcode();

qrcode.setQrcodeErrorCorrect('M');
qrcode.setQrcodeEncodeMode('B');
qrcode.setQrcodeVersion(15);
int width= 235;
int height=235;
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g2=image.createGraphics();
g2.setBackground(Color.WHITE);
g2.clearRect(0,0,235,235);
g2.setColor(Color.BLACK);

byte[] contentbytes=content.getBytes("utf-8");
boolean[][] codeout= qrcode.calQrcode(contentbytes);
for (int i = 0; i <codeout.length; i++) {
for (int j = 0; j < codeout.length; j++) {

if (codeout[j][i]) g2.fillRect(j*3+2,i*3+2,3,3);
}
}
g2.dispose();
image.flush();
File imgFile = new File(filepath);
ImageIO.write(image, "png", imgFile);
}catch (Exception e){
e.printStackTrace();
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM