【Java开发】生成二维码
生活随笔
收集整理的這篇文章主要介紹了
【Java开发】生成二维码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import com.swetake.util.Qrcode;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.charset.StandardCharsets;/*** @ClassName QRCode* @Description TODO 二維碼生成核心類* @Author hulin* @Date 1/10/2020 8:19 PM* @Version 1.0*/
public class QRCode {/*** 二維碼生成** @param content 二維碼存儲的內容* @param imgPath 二維碼存儲的路徑*/public static void getQRCodeImg(String content, String imgPath) {/*** 二維碼基本信息設置*///實例化一個QrcodeQrcode qrcode = new Qrcode();//設置二維碼的排錯率 L:7%; M:15%;Q:25%;H:30%qrcode.setQrcodeErrorCorrect('M');//設置編碼 A:英文 N:數字 B:國際編碼 K:中文qrcode.setQrcodeEncodeMode('B');//設置二維碼的版本qrcode.setQrcodeVersion(15);/*** 開始繪制二維碼*/int width = 235;int height = 235;//畫板BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//畫筆Graphics2D gs = image.createGraphics();//設置背景色gs.setBackground(Color.WHITE);//設置繪制區域gs.clearRect(0, 0, width, height);//設置畫筆的顏色gs.setColor(Color.BLACK);//開始繪制,拿到內容try {byte[] codeOut = content.getBytes(StandardCharsets.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);}}//釋放畫筆gs.dispose();image.flush();//保存ImageIO.write(image, "png", new File(imgPath));System.out.println("二維碼成功生成!");} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {getQRCodeImg("我的第一個二維碼!", "web/img/test.png");getQRCodeImg("https://www.baidu.com", "web/img/baidu.png");}
}
與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的【Java开发】生成二维码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Security基于角色的
- 下一篇: java美元兑换,(Java实现) 美元