java 生成二维码

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

你可能感兴趣的:(java,生成,二维码)