All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.afu.utils.qrcode.Qrcode Maven / Gradle / Ivy

There is a newer version: 0.0.55-RELEASE
Show newest version
package io.afu.utils.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import io.afu.common.exception.BaseException;

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

/**
 * @author: RffanLAB.方露宇
 */
public class Qrcode {

    /**
     *  二维码生成,工具类
     */

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;


    /**
     * 生成二维码文件
     * @param content 二维码包含的内容
     * @param savePath 二维码文件保存路径
     * @throws BaseException 抛出
     */
    public static void encode(String content,String savePath) throws BaseException{
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE,150,150);
            File file = new File(savePath);
            MatrixToImageWriter.writeToFile(bitMatrix,"PNG",file);
        }catch (Exception e){
            throw new BaseException(e);
        }

    }


    /**
     *
     * @param text 文本内容
     * @param width 宽
     * @param height 搞
     * @return byte[]
     * @throws BaseException 生成二维码产生的错误
     */
    public static byte[] getQRCodeImage(String text, int width, int height) throws BaseException {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
            ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
            byte[] pngData = pngOutputStream.toByteArray();
            return pngData;
        }catch (Exception e){
            throw new BaseException(e);
        }
    }










}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy