java生成普通二维码

9次阅读

共计 1930 个字符,预计需要花费 5 分钟才能阅读完成。

二维码是根据一定规则生成,存储信息的小图片。比如可以存储参数存储 url 等内容。扫描之后将能获得这些内容
下文为普通二维码的生成,可自定义二维码的大小,定义二维码中存储的数据内容

1. 下文使用的二维码生成 jar 坐标

     <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
        <version>3.3.2</version>
    </dependency>
   

2. 工具类的定义
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class CodeImageUtil {

// 默认二维码宽度
public static final int WIDTH = 300;
// 默认二维码高度
public static final int HEIGHT = 300;
// 默认二维码文件格式
public static final String FORMAT = "png";
// 二维码参数
public static final Map<EncodeHintType, Object> HINTS = new HashMap<EncodeHintType, Object>();
// 初始化编码格式等参数
static {
    // 字符编码
    HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8");
    HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    // 二维码与图片边距
    HINTS.put(EncodeHintType.MARGIN, 2);
}

/**
 * 
 * @description:功能描述     将二维码写出到输出流中
 * @param content    二维码内容即要存储在二维码中的内容(扫描二维码之后获取的内容)
 * @param stream    输出流
 * @param width    二维码宽
 * @param height    二维码高
 * @throws WriterException
 * @throws IOException
 * @see:需要参见的其它内容
 */
public static void writeToStream(String content, OutputStream stream,
        Integer width, Integer height) throws WriterException, IOException {if(width==null){width=WIDTH;}
    if(height==null){height=HEIGHT;}
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
            BarcodeFormat.QR_CODE, width, height, HINTS);
    MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, stream);
}

}

3.main 中的调用
public void main(String[] arg){

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 生成二维码图片
        CodeImageUtil.writeToStream(url, out, 300, 300);
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        // 将生成的二维码写入图片,也可直接使用流
        String filePath="H:\\file_station\\" + fileName;
        FileOutputStream fos = new FileOutputStream(filePath);
        int length;
        byte[] b = new byte[1024];
        while ((length=in.read(b))>0){fos.write(b,0,length);
        }
        fos.flush();
        in.close();
        fos.close();

}

正文完
 0