美文网首页JavajavaJava学习笔记
java生成二维码例子及Qrcode.jar包(demo小例子)

java生成二维码例子及Qrcode.jar包(demo小例子)

作者: 挑战者666888 | 来源:发表于2016-11-07 13:46 被阅读620次
    java生成二维码例子及Qrcode.jar包

    #######获取地址:
    http://note.youdao.com/noteshare?id=dd9ec8a63ab3b97eba58bf7b32e4a8d9

    package com.module.screen.test;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    
    import javax.imageio.ImageIO;
    
    import com.swetake.util.Qrcode;
    
    public class TestQrcode {
        public static void main(String[] args) {
            getQrcodeImage("http://images.ali213.net/picfile/pic/2013/05/17/927_zzz1.jpg","D:\\tangjinhui.png");
        }
        public static void getQrcodeImage(String content,String imagePath){
            int width = 235;
            int height = 235;
            //实例化一个对象
            Qrcode qrcode = new Qrcode();
            //编码方式
            qrcode.setQrcodeEncodeMode('B');
            //二维码的版本
            qrcode.setQrcodeVersion(15);
            //排错率
            qrcode.setQrcodeErrorCorrect('M');
            
            //创建一个图板
            BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
            //画笔
            Graphics2D gs = image.createGraphics();
            //设置二维码的背景颜色
            gs.setBackground(Color.white);
            gs.setColor(Color.black);
            gs.clearRect(0, 0, width, height);
            
            byte[] codeOut = null;
            try{
                codeOut = content.getBytes("utf-8");
                boolean[][] code = qrcode.calQrcode(codeOut);
                for(int i=0;i<code.length;i++){
                    for(int j=0;j<code.length;j++){
                        if(code[j][i]){
                            gs.fillRect(j*3+2, i*3+2, 3, 3);
                        }
                    }
                }
            File file = new File("C:\\Users\\tangjinhui\\Desktop\\image.png");
            Image srcImage = ImageIO.read(file);
            int width2 = srcImage.getWidth(null);
            int height2 = srcImage.getHeight(null);
            gs.drawImage(srcImage, 83, 83, width2, height2,null);
            //释放资源
            gs.dispose();
            image.flush();
            //写入制定的路径
            ImageIO.write(image, "png",new File(imagePath));
            }catch(Exception e){
                e.printStackTrace();
            }
                    
        }
    }
    

    相关文章

      网友评论

        本文标题:java生成二维码例子及Qrcode.jar包(demo小例子)

        本文链接:https://www.haomeiwen.com/subject/aamvjttx.html