java实现二维码生成

来源:互联网 发布:php 防止ddos攻击 编辑:程序博客网 时间:2024/06/06 09:07
  1. package com.test;  
  2. import com.google.zxing.BarcodeFormat;  
  3. import com.google.zxing.EncodeHintType;  
  4. import com.google.zxing.MultiFormatWriter;  
  5. import com.google.zxing.common.BitMatrix;  
  6.   
  7. import javax.imageio.ImageIO;  
  8. import java.io.File;  
  9. import java.io.OutputStream;  
  10. import java.io.IOException;  
  11. import java.util.HashMap;  
  12. import java.util.Map;  
  13. import java.awt.image.BufferedImage;  
  14. /** 
  15.  * 需要Google  zxing的core包支持   
  16.  * @author lcx 
  17.  * 
  18.  */  
  19.   
  20. public final class MatrixToImageWriter {  
  21.   
  22.   private static final int BLACK = 0xFF000000;  
  23.   private static final int WHITE = 0xFFFFFFFF;  
  24.   
  25.   private MatrixToImageWriter() {}  
  26.   
  27.     
  28.   public static BufferedImage toBufferedImage(BitMatrix matrix) {  
  29.     int width = matrix.getWidth();  
  30.     int height = matrix.getHeight();  
  31.     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  32.     for (int x = 0; x < width; x++) {  
  33.       for (int y = 0; y < height; y++) {  
  34.         image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
  35.       }  
  36.     }  
  37.     return image;  
  38.   }  
  39.   
  40.     
  41.   public static void writeToFile(BitMatrix matrix, String format, File file)  
  42.       throws IOException {  
  43.     BufferedImage image = toBufferedImage(matrix);  
  44.     if (!ImageIO.write(image, format, file)) {  
  45.       throw new IOException("Could not write an image of format " + format + " to " + file);  
  46.     }  
  47.   }  
  48.   
  49.     
  50.   public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)  
  51.       throws IOException {  
  52.     BufferedImage image = toBufferedImage(matrix);  
  53.     if (!ImageIO.write(image, format, stream)) {  
  54.       throw new IOException("Could not write an image of format " + format);  
  55.     }  
  56.   }  
  57.   public static void main(String[] args) {  
  58.       try {          
  59.              String content = "http://www.baidu.com/"; //二维码存储数据  
  60.              String path = "f:\\";//               
  61.              MultiFormatWriter multiFormatWriter = new MultiFormatWriter();  
  62.              Map hints = new HashMap();  
  63.              hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
  64.              BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400400,hints);  
  65.              File file1 = new File(path,"2013.jpg");//图片输出路径  
  66.              MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);  
  67.                
  68.          } catch (Exception e) {  
  69.              e.printStackTrace();  
  70.          }  
  71. }  
  72. }