>  기사  >  Java  >  Java를 사용하여 텍스트로 QR 코드 생성

Java를 사용하여 텍스트로 QR 코드 생성

高洛峰
高洛峰원래의
2017-01-20 14:23:492497검색

소개

주로 goole의 zxing 패키지를 사용합니다. 아래에 샘플 코드가 제공되어 있어 누구나 이해하고 배우기 매우 편리합니다. 이 코드는 예비 프레임워크에 속하며 필요한 기능을 사용할 수 있습니다. 실제 사용량에 따라 최적화됩니다.

첫 번째 단계, maven import zxing

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

두 번째 단계, QR 코드 생성 시작:

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);
 }
}

세 번째 단계, QR 코드 이미지에 텍스트 쓰기:

/**
 * 给二维码图片加上文字
 * @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");
}

네 번째 단계, 메인 메소드에서 테스트, 중간에 텍스트가 있는 2D 코드 코드는 다음과 같습니다. 생성

public static void main(String[] args) throws Exception {
 File qrcFile = new File("/Users/deweixu/","google.jpg");
 writeToFile("www.google.com.hk", "jpg", qrcFile);
 pressText("谷歌", qrcFile, 5, Color.RED, 32);
}

요약

위 내용은 이 글의 전체 내용입니다. 질문이 있으시면 메시지를 남겨서 소통하실 수 있습니다.

Java를 사용하여 텍스트로 QR 코드를 생성하는 것과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.