(一)二维码生成步骤
1.生成一个二维码矩阵
2.给二维码矩阵着色
3.生成二维码文件
(二)代码
1.用goole的core.jar,此处用的core-3.2.0.jar,下载链接http://pan.baidu.com/s/1kTu0EyF
package resume.util; import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable; /** * Created by vinphy on 2015/6/30. */ public class QRCodeUtil { private static final String CHARSET = "utf-8"; private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; /** * 1.生成二维码矩阵 *@param text 要生成二维码的指定字符串; * width宽; height高 */ public static BitMatrix toQRCodeMatrix(String text,Integer width,Integer height){ //1)确定矩阵宽和高,300*300 if(width == null || width < 300){ width = 300; } if (height == null || height <300){ height = 300; } //2)设置二维码图片格式 Hashtable<EncodeHintType,String> hints = new Hashtable<EncodeHintType,String>(); //3)设置内容所使用的编码 hints.put(EncodeHintType.CHARACTER_SET,CHARSET); //4)生成矩阵 BitMatrix matrix = null; try { matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE,width,height,hints); }catch (WriterException e){ e.printStackTrace(); } return matrix; } /** * 2.根据点矩阵生成黑白图 * @param matrix 二维码矩阵 */ public static BufferedImage toBufferedImage(BitMatrix matrix){ //1.得到矩阵长宽 int width = matrix.getWidth(); int height = matrix.getHeight(); //2.得到BufferedIamge实例 BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //3.着色 for (int x = 0; x <width ; x++){ for (int y = 0 ; y < height ; y++){ image.setRGB(x,y,matrix.get(x,y)?BLACK:WHITE); } } return image; } /** * 3.根据矩阵图片格式生成文件 * @param matrix 二维码矩阵; * format 文件格式,如gif; * file 文件 */ public static void writeToFile(BitMatrix matrix,String format,File file){ //1.得到黑白图 BufferedImage image = toBufferedImage(matrix); //2.生成文件 try { if (!ImageIO.write(image,format,file)){ throw new IOException(("Could not write an image of format")+format+"to"+file); } }catch (IOException e){ e.printStackTrace(); } }
}
2.测试
public static void main(String[] args) { //1.要转换的文本 String text = "ningwenhui"; //2.生成文件 File file = new File("d:"+File.separator+"vinphy.gif"); //3.在文件中生成二维码 writeToFile(toQRCodeMatrix(text, null, null),"gif",file); }
Google的Zxing-core.jar包封装了生成黑白图和生成文件的方法,使用如下:
/** * 二维码的生成 * 根据getInfo()生成的六位随机数生成对应的二维码 * */ public void createCode(){ String text = ""+this.getInfo(); int width = 450; int height = 450; /** * 设置二维码的参数 */ String name = "erweima"; String path = "D://create"; HashMap hints = new HashMap(); // 内容所使用编码 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); try { BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE,width,height,hints); // 生成二维码 File file1 = new File(path,name+".jpg"); MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1); } catch (Exception e) { e.printStackTrace(); } }