前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >一个Java实现的把指定字符串生成二维码并保存成图片的代码

一个Java实现的把指定字符串生成二维码并保存成图片的代码

作者头像
Jerry Wang
发布2020-04-29 16:34:11
6780
发布2020-04-29 16:34:11
举报
代码语言:javascript
复制
package qrCode;


import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.IOException;  
import javax.imageio.ImageIO;  
import jp.sourceforge.qrcode.QRCodeDecoder;  
import jp.sourceforge.qrcode.data.QRCodeImage;  
  
public class GucasQRCodeDecoder {  
    public GucasQRCodeDecoder() {  
          
    }  
      
    /** 
     * decode qrcode image. 
     * @param qrcodePicfilePath 
     * @return decoding value. 
     */  
    public static String decode(String qrcodePicfilePath) {  
        File imageFile = new File(qrcodePicfilePath);  
        BufferedImage image = null;  
        try {  
            image = ImageIO.read(imageFile);  
        } catch (IOException e) {  
            System.out.println("Decoding failed, read QRCode image error: " + e.getMessage());  
            return null;  
        }  
        /* 
        try { 
            String decodedData = new String(decoder.decode(new J2SEImageGucas(image)), "GBK"); 
            System.out.println(decodedData); 
        } catch (DecodingFailedException dfe) { 
            System.out.println("Error: " + dfe.getMessage()); 
        } catch (UnsupportedEncodingException e) { 
            e.printStackTrace(); 
        } 
        */  
        QRCodeDecoder decoder = new QRCodeDecoder();  
        String decodedData = new String(decoder.decode(new J2SEImageGucas(image)));  
        return decodedData;  
    }  
  
    public static void main(String[] args) {  
        QRCodeDecoder decoder = new QRCodeDecoder();  
        File imageFile = new File("qrcode//TestQRCode.png");  
        BufferedImage image = null;  
        try {  
            image = ImageIO.read(imageFile);  
        } catch (IOException e) {  
            System.out.println("Error: " + e.getMessage());  
        }  
          
        String decodedData = new String(decoder.decode(new J2SEImageGucas(image)));  
        System.out.println(decodedData);  
    }  
}  
  
class J2SEImageGucas implements QRCodeImage {  
    BufferedImage image;  
  
    public J2SEImageGucas(BufferedImage image) {  
        this.image = image;  
    }  
  
    public int getWidth() {  
        return image.getWidth();  
    }  
  
    public int getHeight() {  
        return image.getHeight();  
    }  
  
    public int getPixel(int x, int y) {  
        return image.getRGB(x, y);  
    }  
}  

代码语言:javascript
复制
package qrCode;



import java.awt.Color;  
import java.awt.Graphics2D;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.IOException;  
  
import javax.imageio.ImageIO;  
import com.swetake.util.Qrcode;  
  
public class GucasQRCodeEncoder {  
      
    public static int max_data_size_small = 84;  
    public static int max_data_size_large = 500;  
      
    /** 
     *  
     * @param srcValue 
     * @param qrcodePicfilePath 
     * @return 
     */  
    public static boolean encode(String srcValue, String qrcodePicfilePath) {  
        return  encode_84(srcValue, qrcodePicfilePath);  
    }  
      
    /** 
     * Encoding the information to a QRCode, size of the information must be less than 84 byte. 
     * @param srcValue 
     * @param qrcodePicfilePath 
     * @return 
     */  
    public static boolean encode_84(String srcValue, String qrcodePicfilePath) {  
        int MAX_DATA_LENGTH = max_data_size_small; // the max size of QR code data source
        byte[] d = srcValue.getBytes();  
        int dataLength = d.length;  
        int imageWidth = 113; // image size must >= QR code size, or else it will 
                              // not be correctly decoded
        int imageHeight = imageWidth;  
        BufferedImage bi = new BufferedImage(imageWidth, imageHeight,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics2D g = bi.createGraphics();  
        g.setBackground(Color.WHITE);  
        g.clearRect(0, 0, imageWidth, imageHeight);  
        g.setColor(Color.BLACK);  
        if (dataLength > 0 && dataLength <= MAX_DATA_LENGTH) {  

            Qrcode qrcode = new Qrcode();  
            //错误修正容量   
            //L水平   7%的字码可被修正  
            //M水平   15%的字码可被修正  
            //Q水平   25%的字码可被修正  
            //H水平   30%的字码可被修正  
            //QR码有容错能力,QR码图形如果有破损,仍然可以被机器读取内容,最高可以到7%~30%面积破损仍可被读取。  
            
            qrcode.setQrcodeErrorCorrect('M'); // L, Q, H, by default
            
            qrcode.setQrcodeEncodeMode('B'); // A, N, Ĭ��  
            qrcode.setQrcodeVersion(5); // 37 bytes, (37-1)*3+2+3-1+1 = 113
            boolean[][] b = qrcode.calQrcode(d);  
            int qrcodeDataLen = b.length;  
            for (int i = 0; i < qrcodeDataLen; i++) {  
                for (int j = 0; j < qrcodeDataLen; j++) {  
                    if (b[j][i]) {  
                        g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3); 
                        
                    }  
                }  
            }  
            System.out.println("QR code data length" + qrcodeDataLen);  
        } else {  
            System.out.println("Generate QRCode image error! Data size is " + dataLength +", it is lager than 84 bytes.");  
            return false;  
        }  
        g.dispose();  
        bi.flush();  
        /* generate image */  
        File f = new File(qrcodePicfilePath);  
        String suffix = f.getName().substring(f.getName().indexOf(".")+1, f.getName().length());  
        try {  
            ImageIO.write(bi, suffix, f); //"png"  
        } catch (IOException ioe) {  
            System.out.println("Generate QRCode image error!" + ioe.getMessage());  
            return false;  
        }  
  
        return true;  
    }  
      
    /** 
     * Encoding the information to a QRCode, size of the information must be less tah 500 byte. 
     * @param srcValue 
     * @param qrcodePicfilePath 
     * @return 
     */  
    public static boolean encode_500(String srcValue, String qrcodePicfilePath) {  
        int MAX_DATA_LENGTH = max_data_size_large; 
        byte[] d = srcValue.getBytes();  
        int dataLength = d.length;  
        int imageWidth = 269; 
        int imageHeight = imageWidth;  
        BufferedImage bi = new BufferedImage(imageWidth, imageHeight,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics2D g = bi.createGraphics();  
        g.setBackground(Color.WHITE);  
        g.clearRect(0, 0, imageWidth, imageHeight);  
        g.setColor(Color.BLACK);  
        if (dataLength > 0 && dataLength <= MAX_DATA_LENGTH) {  
            /* ��ɶ�ά�� */  
            Qrcode qrcode = new Qrcode();  
            qrcode.setQrcodeErrorCorrect('M'); 
            qrcode.setQrcodeEncodeMode('B'); 
            qrcode.setQrcodeVersion(18); // 0<= version <=40; 89�ֽ�,  
                                            // (89-1)*3+2+3-1+1 = 269  
            boolean[][] b = qrcode.calQrcode(d);  
            int qrcodeDataLen = b.length;  
            for (int i = 0; i < qrcodeDataLen; i++) {  
                for (int j = 0; j < qrcodeDataLen; j++) {  
                    if (b[j][i]) {  
                        g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3); 
                    }  
                }  
            }  
            System.out.println("QR code size" + qrcodeDataLen);  
        } else {  
            return false;  
        }  
        g.dispose();  
        bi.flush();  
        /* generate image */  
        File f = new File(qrcodePicfilePath);  
        String suffix = f.getName().substring(f.getName().indexOf(".")+1, f.getName().length());  
        System.out.println(suffix);  
        try {  
            ImageIO.write(bi, suffix, f); //"png"  
        } catch (IOException ioe) {  
            System.out.println("Generate QRCode image error!" + ioe.getMessage());  
            return false;  
        }  
  
        return true;  
    }  
      
    public static void main(String[] args) throws Exception {  
        System.out.println("trying to encode QRCode...");
        String data = "亲,这是用来生成二维码的测试字符串。。。";  
        System.out.println("total number of source string: " + data.getBytes().length);  
        GucasQRCodeEncoder.encode(data, "c:\\temp\\A1.JPG");  
        System.out.println("encoded string: " + GucasQRCodeDecoder.decode("c:\\temp\\A1.JPG"));  
    }  
}  

代码语言:javascript
复制
package qrCode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class Main {
    public static void main(String[] args) {
        ByteArrayOutputStream out = QRCode.from("Hello World").to(ImageType.PNG).stream();

        try {
            FileOutputStream fout = new FileOutputStream(new File(
                    "C:\\temp\\QR_Code.JPG"));

            fout.write(out.toByteArray());

            fout.flush();
            fout.close();

        } catch (FileNotFoundException e) {
            // Do Logging
        } catch (IOException e) {
            // Do Logging
        }
    }
    /* 除了使用QRGen的API来生成数据流,我们还可以使用下面的API来创建QR码:
// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();

// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();

// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();

// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();


在Java中生成网站链接(URL)的QR码

QR 码最常见的应用便是为网站中一个特定的网页或下载页带来流量。因此,QR码常常会编码URL或网站地址,用户可以通过手机摄像头扫描,并在其浏览器中打开。URL可以直接编码在QR码中。在上面的的Hello World示例中,只需把“Hello World”这个字符串替换为需要编码的URL。下面是代码片段:
ByteArrayOutputStream out = QRCode.from("http://viralpatel.net").to(ImageType.PNG).stream();

*/
    
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档