关于用Java实现二维码的生成
2024-09-13 15:09:35
昨天晚上看了一个视频讲的是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();
}
}
}
最新文章
- [LeetCode] Repeated Substring Pattern 重复子字符串模式
- fiddler监听127.0.0.1或localhost
- [POJ1328]Radar Installation
- iOS开发多线程篇—线程间的通信
- Java-note-字符串连接
- Chrome 插件vimium快捷键大全
- The first day,I get a blogs!!
- [shiro学习笔记]第二节 shiro与web融合实现一个简单的授权认证
- 死磕 java集合之ConcurrentHashMap源码分析(三)
- 虚拟机中使用centos7搭建ftp服务器
- HBase学习——4.HBase过滤器
- Axure安装、破解、汉化全套
- Codeforces 982E Billiard 扩展欧几里德
- Vue实现用户自定义上传头像裁剪
- Oracle备份恢复简单过程以及中间的坑.
- ZOC7 for Mac连接CentOS7无法输入中文问题
- windows 清理利器
- javascript私有静态成员
- 【bzoj3451】Tyvj1953 Normal 期望+树的点分治+FFT
- jquery.sparkline.js简介