java 生成二维码

编程技术  /  houtizong 发布于 3年前   140
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);
     }
    }
}

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客