We drop the effect:
QR codes can be seen everywhere now, which greatly facilitates our life, but are you curious about it?
In fact, we can also make a simple QR code. Before we start making it, we need to add a background.
Any computer information is actually composed of a series of 0/1 numbers.
Therefore, based on this, our general idea has been completed: convert all the information into binary codes, then define 0 as black and 1 as white, and draw a solid cube to form our QR code as a whole.
1. Convert binary method
We need to understand that the binary code
//将字符串信息转化为二进制码,存在 int数组里
public void change() {
//存储单个字符的字符串
String solo = new String();
//读取整个字符串
for (int i = 0; i < input.length(); i++) {
//得到单个字符
char a = input.charAt(i);
//将字符转换为二进制码
int c = (int) a;
solo = bin(c);
//让int数组存入,因为我们的得到是字符串,所以需要判断后存入
//一个字符串存入了16个0/1.
for (int j = 0; j < 16; j++) {
if (solo.charAt(j) == '0') {
bins.add(0);
} else {
bins.add(1);
}
}
}
System.out.println(bins);
}
//将char转化为二进制码
public String bin(int a) {
//存储单个字符的字符串
String bin = new String();
//利用位运算,得到最后一位,然后再将数左移一位
//字符采取的是char类型,一共有16bit,所以字符串要连接16个0/1。
for (int i = 0; i < 16; i++) {
//注意二进制码加入位置
if ((a & 1) == 0) {
bin = "0" + bin;
} else {
bin = "1" + bin;
}
a = a >> 1;
}
return bin;
}
2. Drawing method
//开始绘制
@Override
public void paint(Graphics g) {
super.paint(g);
//用于使方块间隔
int wid = 0;
//用于换行
int hig = 0;
//遍历存入所有二进制码的数组
for (int i = 0; i < bins.size(); i++) {
if (bins.get(i) == 0) {
bg.setColor(Color.BLACK);
} else {
bg.setColor(Color.WHITE);
}
//size为方块尺寸
bg.fillRect(size * wid, size * hig, size, size);
wid++;
//以十六个二进制码为一行,代表一个字符
if (wid == 16) {
wid = 0;
hig++;
}
}
g.drawImage(qrBuff, 200, 350, null);
}
3. Recognition method (put the QR code in the cached image for recognition)
public void identify(BufferedImage qrbuff) {
//存各种颜色int值
int rgb, red, green, blue, gray;
//存字符的int值
int num = 0;
//存储字符串
String out = null;
//为了防止边界干扰,我们将起点放在实心正方形的中心
for (int j = size / 2; j < qrbuff.getHeight(); j += size) {
for (int i = size / 2; i < qrBuff.getWidth(); i += size) {
//因为有时候图片会损失,所以不一定是纯白和纯黑,故我们引进灰度值,更好判断黑白
rgb = qrBuff.getRGB(i, j);
red = (rgb >> 16) & 255;
green = (rgb >> 8) & 255;
blue = (rgb >> 0) & 255;
gray = (red + green + blue) / 3;
if (gray > 127) {
//二进制位上为1
num = num * 2 + 1;
} else {
//二进制位上为0
num = num *2;
}
}
//防止字符串出现null。
//将int转化为所需的char字符,再连接到字符串上
if(out == null){
out = ""+(char)num;
}else {
out += (char) num;
}
num = 0;
}
4. Interface design
It has been completely rotten, there are only two points worth noting:
1. Using internal listeners can greatly reduce data transfer
ActionListener ac = new ActionListener() {
//识别二维码
@Override
public void actionPerformed(ActionEvent e) {
identify(qrBuff);
}
2. Use a multi-line text edit box:
JTextArea jt = new JTextArea();
//设置文本框大小
jt.setPreferredSize(dim);
//设置文本框字体
jt.setFont(new Font("宋体", Font.BOLD,30));
//设置换行与输出间隔一行
jt.setLineWrap(true);
jt.append(out+ "\n");
And that's it! We're done! ! !