生成一个url的二维码

来源:互联网 发布:学c4d 知乎 编辑:程序博客网 时间:2024/04/30 10:59

1.调用的是zxing中的core架包 http://download.csdn.net/detail/u013946257/9411484

2.代码如下:

package app.core.qrCode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public class Test {
 private static final int width = 300;
 private static final int height = 300;
 private static final String format = "jpg";
 private static final int BLACK = 0xFF000000;
 private static final int WHITE = 0xFFFFFFFF;
 
 public static void main (String[] args) throws IOException, WriterException {
  String text = "http://www.timeface.cn";
  BufferedImage image = createQRCode(text);
 }
 
 /**
  *
  * @param text 需要生成二维码的预览地址
  * @return 二维码图片
  * @throws WriterException
  * @throws IOException
  */
 public static BufferedImage createQRCode(String text) throws WriterException, IOException {
  // 生成二维码文件名
  String name = "";
  Pattern p = Pattern.compile("\\/(\\d)+\\/"); 
  Matcher m = p.matcher(text);
  if (m.find()) { 
    name = m.group().substring(1, m.group().length() -1);
  }
  
  Hashtable hints = new Hashtable();
  // 内容所使用编码
  hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
  BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
  
  // 去除二维码边距
  int[] rec = bitMatrix.getEnclosingRectangle();
  int newWidth = rec[2] + 1;
  int newHeight = rec[3] + 1;
  BitMatrix newBitMatrix = new BitMatrix(newWidth, newHeight);
  newBitMatrix.clear();
  for (int i = 0; i < newWidth; i++) {
   for (int j = 0; j < newHeight; j++) {
    if (bitMatrix.get(i + rec[0], j + rec[1])) {
     newBitMatrix.set(i, j);
    }
   }
  }
  
  // 生成二维码
  File outputFile = new File("d:" + File.separator + name + "." + format);
  int width = newBitMatrix.getWidth();
  int height = newBitMatrix.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, newBitMatrix.get(x, y) ? BLACK : WHITE);
   }
  }
  
  // 在相应路径输出图片
  if (!ImageIO.write(image, format, outputFile)) {
   throw new IOException("Could not write an image of format " + format + " to " + outputFile);
  }
  
  return image;
 }
}



0 0
原创粉丝点击