二维码的生成
根据二进制码的顺序: 0绘制一个白块 1绘制一个黑块
// ASCII 128 byte的正数部分 0-127
String str=“https://bilibili.com”;
// 取出单个的字符
String binaryStr=Integer.toBinaryString(); // 将不规则的字符串二进制码
// 补码 补全 8bit 在前面补0
// 存储转好的二进制码
public class QRCode {
public String[] StringtoBinaryString() {
//取出单个字符转成二进制码,但是转成的二进制码位数都不一样
String s="www.zhihu.com";
String[] StringArray=new String[s.length()];
for(int i=0;i<s.length();i++) {
char c= s.charAt(i);
String binaryStr=Integer.toBinaryString(c);
//将不规则的字符串二进制码用补码补全,8bit,因为是字符串所以可以这样表示
while(binaryStr.length()<8) {
binaryStr=0+binaryStr;
}
System.out.print(binaryStr+"\n");
StringArray[i]=binaryStr;
}
return StringArray;
}
}
public class QRCodeUI extends JFrame{
String[] StringArray= {};
public static void main(String[] args) {
QRCode qrcode=new QRCode();
QRCodeUI ui =new QRCodeUI();
ui.StringArray=qrcode.StringtoBinaryString();
ui.setTitle ("二维码显示");
ui.setVisible(true);
ui.setSize (800,600);
ui.setDefaultCloseOperation (EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
for(int i=0;i<StringArray.length;i++) {
String str =StringArray[i];
for(int j=0;j<str.length();j++) {
char c=str.charAt(j);
if(c=='0') {
g.setColor(Color.WHITE);
}else {
g.setColor(Color.BLACK);
}
g.fillRect(50+i*30, 100+j*30, 30, 30);
}
}
}
}
二维码的识别
/*
* 在线写出下面识别
还原为字符串
1: 图片的宽度/字数=格子宽度
2: 获取图片转为二位像素数组
3:隔着宽度 取 像素值 白色=0/黑色=1;
4: 一列就可以获取一个二进制码 >> char
*/
public class toCode {
public static void main(String[] args) {
toCode tocode =new toCode();
JFileChooser jfc =new JFileChooser();
FileNameExtensionFilter filter =
new FileNameExtensionFilter
("图片文件(jpg、png、jpeg、gif、bmp、heic)","jpg","png","jpeg","gif","bmp","heic");
jfc.setFileFilter(filter);
jfc.showOpenDialog(null);
File file =jfc.getSelectedFile();
String code=tocode.getImagePixArray(file);
}
String getImagePixArray(File file){
BufferedImage bufferedimage =null;
try {
bufferedimage=ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int w=bufferedimage.getWidth();
int h =bufferedimage.getHeight();
int xw=w/20;
String s="";
int[][] imagearr=new int[w][h];
for(int i=xw/2;i<w;i+=xw) {
s="";
for(int j=xw/2;j<xw*8;j+=xw) {
imagearr[i][j]=bufferedimage.getRGB(i, j);
Color c=new Color(imagearr[i][j]);
int blue =c.getBlue();
int red =c.getRed();
int green=c.getGreen();
int gray =(blue+green +red)/3;
if(gray>150) {
s+="0";
}else {
s+="1";
}
}
// System.out.print(s+"\n");
//将字符串s亿二进制的形式输出
int codetoString =Integer.parseInt(s,2);
System.out.print((char)codetoString);
}
return s;
}
}