首页 > 学院 > 开发设计 > 正文

关于用Java实现二维码的生成

2019-11-14 23:37:28
字体:
来源:转载
供稿:网友
关于用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();        }    }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表