java 生成二维码ITeye - 凯发娱乐

java 生成二维码ITeye

2019年03月13日13时45分59秒 | 作者: 乐琴 | 标签: 二维码,生成,郑文彬 | 浏览: 1103

package com.zheng.wen.Constroller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Controller;

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

@Controller
public class IndexController {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
public static void main(String[] args) throws Exception {
  String text = "郑文彬";
  int width = 300;
  int height = 300;
  //二维码的图片格式
  String format = "gif";
  Map EncodeHintType, String hints = new HashMap EncodeHintType, String
  //内容所运用编码
  hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
  BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
  BarcodeFormat.QR_CODE, width, height, hints);
  //生成二维码
  File outputFile = new File("d:"+File.separator+"new.gif");
  writeToFile(bitMatrix, format, outputFile);
  }


//生成二维码图片
public static BufferedImage toBufferedImage(BitMatrix matrix){
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage imge = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
for(int i=0;i width;i++){
for(int y=0;y height;y++){
imge.setRGB(i, y, matrix.get(i,y)? BLACK : WHITE);
}
}
return imge;
}

//保存为本地文件
public  static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
  BufferedImage image = toBufferedImage(matrix);
  if (!ImageIO.write(image, format, file)) {
  throw new IOException("Could not write an image of format " + format + " to " + file);
  }
  }
 
//二维码转换为流 
  public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
  BufferedImage image = toBufferedImage(matrix);
  if (!ImageIO.write(image, format, stream)) {
  throw new IOException("Could not write an image of format " + format);
  }
  }
}
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表凯发娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章

阅读排行

  • 1

    Nodejs的express路由规矩ITeye

    路由,中间件,一般
  • 2

    java 生成二维码ITeye

    二维码,生成,郑文彬
  • 3

    Struts2 拦截器ITeye

    拦截器,没有,回来
  • 4
  • 5

    Servlet 接口ITeye

    用户名,暗码
  • 6
  • 7
  • 8

    Java日志体系ITeye

    不到,用于,配置文件
  • 9
  • 10