这两天想了解一下二维码是怎样生成的。然后在网上看了很多资料,也有很多源码可以直接用的。我也没有自己写,也是拿着源码进行看和修改的,然后生成自己想要的二维码和一维码,还是很不错的,所以分享一下。
首先第一步,需要导入jar包,我把我用的jar包放上来吧

jar包下载链接:http://download.csdn.net/download/qq_27790011/10046325

将包导入好项目之后就可以开始写代码了,先来谈谈一个简单的生成二维码和一维码。想直接使用的可以复制代码之直接可以用。
下面是MatrixUtil 类,全部生成一维码和二维码的方法都在里面,不过都是生成最简单的样式,样式可以自己修改。

package com.zlf.qrcode2;import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
//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.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.awt.image.BufferedImage; /*** 使用ZXing2.3,生成条码的辅助类。可以编码、解码。编码使用code包,解码需要javase包。*/
public final class MatrixUtil { private static final String CHARSET = "utf-8"; private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; /*** 禁止生成实例,生成实例也没有意义。*/ private MatrixUtil() { } /*** 生成矩阵,是一个简单的函数,参数固定,更多的是使用示范。   * @param text* @return*/ public static BitMatrix toQRCodeMatrix(String text, Integer width, Integer height) { if (width == null || width < 300) { width = 300; } if (height == null || height < 300) { height = 300; } // 二维码的图片格式 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); // 内容所使用编码 hints.put(EncodeHintType.CHARACTER_SET, CHARSET); BitMatrix bitMatrix = null; try { bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); } catch (WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 生成二维码 // File outputFile = new File("d:"+File.separator+"new.gif"); // MatrixUtil.writeToFile(bitMatrix, format, outputFile); return bitMatrix; } /*** 将指定的字符串生成二维码图片。简单的使用示例。    * @param text* @param file* @param format* @return*/ public boolean toQrcodeFile(String text, File file, String format) { BitMatrix matrix = toQRCodeMatrix(text, null, null); if (matrix != null) { try { writeToFile(matrix, format, file); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; } /*** 根据点矩阵生成黑白图。 */ public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 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; } /*** 将字符串编成一维条码的矩阵  * @param str* @param width* @param height* @return*/ public static BitMatrix toBarCodeMatrix(String str, Integer width, Integer height) { if (width == null || width < 200) { width = 200; } if (height == null || height < 50) { height = 50; } try { // 文字编码 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); BitMatrix bitMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.CODE_128, width, height, hints); return bitMatrix; } catch (Exception e) { e.printStackTrace(); } return null; } /*** 根据矩阵、图片格式,生成文件。*/ 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); } } /*** 解码,需要javase包。* @param file* @return*/ /*public static String decode(File file) { BufferedImage image; try { if (file == null || file.exists() == false) { throw new Exception(" File not found:" + file.getPath()); } image = ImageIO.read(file); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; // 解码设置编码方式为:utf-8, Hashtable hints = new Hashtable(); hints.put(DecodeHintType.CHARACTER_SET, CHARSET); result = new MultiFormatReader().decode(bitmap, hints); return result.getText(); } catch (Exception e) { e.printStackTrace(); } return null; } */
}

接下来是Test测试类,代码更简单。

package com.zlf.qrcode2;import java.io.File; public class Test {   /*** 测试函数。简单地将指定的字符串生成二维码图片。*/ public static void main(String[] args) throws Exception {   String text = "1234567890";   String result; String format = "jpg";   //生成二维码   File outputFile = new File("j:"+File.separator+"rqcode.jpg");   MatrixUtil.writeToFile(MatrixUtil.toQRCodeMatrix(text, null, null), format, outputFile);   System.out.println("success1");//result = MatrixUtil.decode(outputFile); //System.out.println(result); //生成条形码 outputFile = new File("j:"+File.separator+"barcode.jpg");   MatrixUtil.writeToFile(MatrixUtil.toBarCodeMatrix(text, null, null), format, outputFile); System.out.println("success2");//result = MatrixUtil.decode(outputFile); //System.out.println(result); }   }   

一维码和二维码效果图

接下来主要讲一下二维码的生成吧,因为现在二维码比较火,动不动就手机扫一扫。为了制作一个稍微有特点的二维码。我另起了一个项目,不过jar包还是通用的。然后有这几个类。MatrixToImageWriter类QRCodeFactory类和测试类Qrest

MatrixToImageWriter类主要的功能也是生成二维码图片

package com.zlf.qrcode;import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;/*二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用,当然你也可以自己写个生产条形码的基类*/
public class MatrixToImageWriter {private static final int BLACK = 0xFF000000;//用于设置图案的颜色private static final int WHITE = 0xFFFFFFFF; //用于背景色private MatrixToImageWriter() {}public static BufferedImage toBufferedImage(BitMatrix matrix) {int width = matrix.getWidth();int height = matrix.getHeight();BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y,  (matrix.get(x, y) ? BLACK : WHITE));
//                image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));}}return image;}public static void writeToFile(BitMatrix matrix, String format, File file,String logUri) throws IOException {System.out.println("write to file");BufferedImage image = toBufferedImage(matrix);//设置logo图标QRCodeFactory logoConfig = new QRCodeFactory();image = logoConfig.setMatrixLogo(image, logUri);if (!ImageIO.write(image, format, file)) {System.out.println("生成图片失败");throw new IOException("Could not write an image of format " + format + " to " + file);}else{System.out.println("图片生成成功!");}}public static void writeToStream(BitMatrix matrix, String format, OutputStream stream,String logUri) throws IOException {BufferedImage image = toBufferedImage(matrix);//设置logo图标QRCodeFactory logoConfig = new QRCodeFactory();image = logoConfig.setMatrixLogo(image, logUri);if (!ImageIO.write(image, format, stream)) {throw new IOException("Could not write an image of format " + format);}}
}

QRCodeFactory类的功能主要是编写自己特定制作,比如给二维码添加一个logo,给二维码添加文字说明。

package com.zlf.qrcode;import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/*** 本类用于对我们二维码进行参数的设定,生成我们的二维码:* @author kingwen*/
public class QRCodeFactory {/*** 给生成的二维码添加中间的logo* @param matrixImage 生成的二维码* @param logUri      logo地址* @return            带有logo的二维码* @throws IOException logo地址找不到会有io异常*/public BufferedImage setMatrixLogo(BufferedImage matrixImage,String logUri) throws IOException{/*** 读取二维码图片,并构建绘图对象*/Graphics2D g2 = matrixImage.createGraphics(); int matrixWidth = matrixImage.getWidth();int matrixHeigh = matrixImage.getHeight();/*** 读取Logo图片*/BufferedImage logo = ImageIO.read(new File(logUri));//开始绘制图片g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制边框 BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); // 设置笔画对象g2.setStroke(stroke);//指定弧度的圆角矩形RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);g2.setColor(Color.white);// 绘制圆弧矩形g2.draw(round);//设置logo 有一道灰色边框BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); // 设置笔画对象g2.setStroke(stroke2);RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);g2.setColor(new Color(128,128,128));g2.draw(round2);// 绘制圆弧矩形Font font = new Font("Freestyle Script", Font.BOLD, 80);g2.setFont(font);g2.drawString("my love", matrixWidth/5*1+50, matrixHeigh/5*4-10);g2.dispose();matrixImage.flush() ;return matrixImage ;}/*** 创建我们的二维码图片* @param content            二维码内容* @param format             生成二维码的格式* @param outFileUri         二维码的生成地址* @param logUri             二维码中间logo的地址* @param size               用于设定图片大小(可变参数,宽,高)* @throws IOException       抛出io异常* @throws WriterException   抛出书写异常*/public  void CreatQrImage(String content,String format,String outFileUri,String logUri, int ...size) throws IOException, WriterException{int width = 430; // 二维码图片宽度 430 int height = 430; // 二维码图片高度430    //如果存储大小的不为空,那么对我们图片的大小进行设定if(size.length==2){width=size[0];height=size[1];}else if(size.length==1){width=height=size[0];}Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();// 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 内容所使用字符集编码hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    //hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值//hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数BitMatrix bitMatrix = new MultiFormatWriter().encode(content,//要编码的内容//编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,//Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,//MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSIONBarcodeFormat.QR_CODE,width, //条形码的宽度height, //条形码的高度hints);//生成条形码时的一些配置,此项可选// 生成二维码图片文件File outputFile = new File(outFileUri);//指定输出路径    System.out.println("输出文件路径为"+outputFile.getPath());MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile,logUri);}
}

接下来就是测试Qrest类了,

package com.zlf.qrcode;import java.io.IOException;import com.google.zxing.WriterException;public class Qrest {public static void main(String[] args) {String content="我莫名奇妙的笑了,只因为想到了你。";String logUri="J:/logs/1.jpg"; //J:\\logs\\author.jpgString outFileUri="J:/logs/qtCode1.jpg";int[]  size=new int[]{430,430};String format = "jpg";  try {new QRCodeFactory().CreatQrImage(content, format, outFileUri, logUri,size);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (WriterException e) {// TODO Auto-generated catch blocke.printStackTrace();}   }}

这些代码也可以直接复制直接使用的。,现在给看一下我做出来的效果图。

参考的文章比较多,现在也记不得网址了,就不粘出来了,如果有侵权的联系我删除。

java生成一维码和二维码相关推荐

  1. Java生成微信小程序二维码

    Java生成微信小程序二维码 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.Byt ...

  2. Java生成中间logo的二维码(还可以加上二维码名称哦)

    最近有负责微信开发,对于微信开发的项目,肯定少不了二维码啦,正好有个这样的需求,这对不同的商品生成一个二维码,扫码即刻下单.博主就弄了一个二维码生成的工具类. 弄出来之后,产品经理又说了,中间放上公司 ...

  3. Java生成微信小程序二维码,5种实现方式,一个比一个简单

    文章目录 前言 先看官网 一.JDK自带的URLConnection方式 二.Apache的HttpClient方式 三.okhttp3方式 四.Unirest方式 五.RestTemplate方式 ...

  4. 【java】Java生成微信小程序二维码

    文章目录 前言 应用场景 微信小程序官网 1.RestTemplate方式 核心代码 getAccessToken 2. Unirest方式 Maven依赖 核心代码 3. okhttp3方式 Mav ...

  5. Java 生成微信扫描的二维码,跳转到指定网址,图片增加二维码及文字水印

    两种场景: 1.图片海报中加二维码 2.二维码中间加入指定图标 注意点:字体要再设置一下清晰度,要不特别模糊. graph.setRenderingHint(RenderingHints.KEY_TE ...

  6. JAVA生成带图标的二维码(产品溯源码)

    一.效果图 二.代码示例: 1. 引入依赖 <!--谷歌提供的二维码插件--><dependency><groupId>com.google.zxing</g ...

  7. 用java生成一个简单的二维码

    转自:原来Java生成二维码这么简单_一个爱运动的程序员的博客-CSDN博客_java二维码生成 首先创建一个maven项目 pom.xml引入zxing依赖 <dependency>&l ...

  8. Java生成微信小程序二维码、上传至阿里云OSS

    依赖 <!-- 阿里云oss依赖 --><dependency><groupId>com.aliyun.oss</groupId><artifac ...

  9. java生成微信小程序二维码(自定义带参)

    准备工作: 1:获取微信小程序apiKey 2:获取微信小程序密钥 3:获取微信小程序页面链接 pom依赖: <dependency><groupId>com.alibaba& ...

最新文章

  1. 树链剖分——线段树区间合并bzoj染色
  2. 《高性能科学与工程计算》——3.7 习题
  3. 微信小程序把玩(二十七)audio组件
  4. 快速搭建一个restful风格的springboot项目
  5. 探讨mutex与semaphore
  6. 最新版dotnet-cli下的ASP.NET Core和asp.net mvc【RC2尝鲜】
  7. Java ByteBuffer –速成课程
  8. css flexbox模型_代码简介:CSS Flexbox有点像旅行
  9. 禁止电商平台二选一、遛狗必栓绳!5月起有这些新规定
  10. ubuntu之解决安装python3.6.4后出现error while loading shared libraries: libpython3.6m.so.1.0的问题
  11. android javamail客户端获取慢_QQ音乐Android客户端Web页面通用性能优化实践
  12. 自动交易软件的功能特点能满足哪些要求?
  13. AlphaGo Zero算法讲解
  14. Lakes.AERMOD.View.v8.9.0 1CD大气扩散模型软件包
  15. 路由器温度测试软件,教你增强小米路由WEB管理(一)——添加CPU温度显示
  16. 基于智能手机传感器数据的人类行为识别
  17. win10开机启动ps1脚本
  18. 真香,如何关闭微信朋友圈的广告
  19. 美国佐治亚大学计算机专业,美国佐治亚大学排名
  20. 11个你可能不知道的Python库

热门文章

  1. 桐爷开车 线性动态规划
  2. 组织培训管理之新人练习计划
  3. 【51nod】【单调栈】扔盘子
  4. 如何使用UltralSO制作系统UEFI启动盘
  5. vjudge11.10
  6. 百度AI深度学习课程 作业1--爬取《乘风破浪的姐姐》所有选手信息
  7. java9 揭秘 jlink_Java 中的Jlink详解
  8. 2007年度網絡最新警句,樂不死你
  9. Python语法第六讲 for循环
  10. Fedora17亮度调节,双显卡用户切换,无线网卡