應用Java生成帶有文字的二維碼。本站提示廣大學習愛好者:(應用Java生成帶有文字的二維碼)文章只能為提供參考,不一定能成為您想要的結果。以下是應用Java生成帶有文字的二維碼正文
引見
重要應用了goole的zxing包,上面給出了示例代碼,很便利年夜家的懂得和進修,代碼都屬於初步框架,功效有了,須要依據現實應用情形完美優化。
第一步、maven導入zxing
<dependency> <groupId>com.谷歌.zxing</groupId> <artifactId>core</artifactId> <version>3.2.1</version> </dependency>
第二步、開端生成二維碼:
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
/**
* 把生成的二維碼存入到圖片中
* @param matrix zxing包下的二維碼類
* @return
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
/**
* 生成二維碼並寫入文件
* @param content 掃描二維碼的內容
* @param format 圖片格局 jpg
* @param file 文件
* @throws Exception
*/
public static void writeToFile(String content, String format, File file)
throws Exception {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
@SuppressWarnings("rawtypes")
Map hints = new HashMap();
//設置UTF-8, 避免中文亂碼
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//設置二維碼周圍白色區域的年夜小
hints.put(EncodeHintType.MARGIN,1);
//設置二維碼的容錯性
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//畫二維碼
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = toBufferedImage(bitMatrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
第三步、把文字寫入二維碼圖片中:
/**
* 給二維碼圖片加上文字
* @param pressText 文字
* @param qrFile 二維碼文件
* @param fontStyle
* @param color
* @param fontSize
*/
public static void pressText(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
pressText = new String(pressText.getBytes(), "utf-8");
Image src = ImageIO.read(qrFile);
int imageW = src.getWidth(null);
int imageH = src.getHeight(null);
BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, imageW, imageH, null);
//設置畫筆的色彩
g.setColor(color);
//設置字體
Font font = new Font("宋體", fontStyle, fontSize);
FontMetrics metrics = g.getFontMetrics(font);
//文字在圖片中的坐標 這裡設置在中央
int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
int startY = HEIGHT/2;
g.setFont(font);
g.drawString(pressText, startX, startY);
g.dispose();
FileOutputStream out = new FileOutputStream(qrFile);
ImageIO.write(image, "JPEG", out);
out.close();
System.out.println("image press success");
}
第四步、在main辦法中測試一下,一個中央帶文字的二維碼就生成了
public static void main(String[] args) throws Exception {
File qrcFile = new File("/Users/deweixu/","谷歌.jpg");
writeToFile("www.谷歌.com.hk", "jpg", qrcFile);
pressText("谷歌", qrcFile, 5, Color.RED, 32);
}
總結
以上就是這篇文章的全體內容了,願望本文的內容對年夜家的進修或許任務能帶來必定的贊助,假如有疑問年夜家可以留言交換。