通过JAVA生成二维码的方式主要有两种(ZXing和QRCode),此次实现的代码采用的是google公司提供的ZXing二维码生成器。
第一步:导包
第二步:代码实现
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSONObject; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; /** * 二维码生成测试 * @author Administrator * */ public class QRCodeTest { //生成二维码 public void QRcode() throws WriterException, IOException{ String FileName = "ZXing.jpg"; //文件名称 String FilePath = "d:/"; //文件保存地址 /** * 可以通过json格式来进行数据跳转,同样也可以通过String来进行写相关的代码或信息 */ //创建JSON解析器(阿里巴巴) //JSONObject json = new JSONObject(); //json.put("baidu", "https://www.baidu.com/"); //将JSON数据转换成字符类型 //String content = json.toJSONString(); //设置跳转地址(如果需要直接跳转应直接采用String 数据类型进行跳转) String content = "https://www.baidu.com/"; int width = 200; //设置二维码图片宽度 int height = 200; //设置二维码图片高度 String format = "jpg"; //设置二维码图像类型 Maphint = new HashMap (); //设置输出格式 hint.put(EncodeHintType.CHARACTER_SET, "UTF8"); //生成矩形(MultiFormatWriter是一个工厂类,根据传入的参数生相应的条码) BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hint); //指定图像生成后保存路径并指定名字 Path path = FileSystems.getDefault().getPath(FilePath, FileName); //写出编码到指定路径(传入参数代码的格式、图像的类型、图像生成后的路径),该方法在javase-3.0.jar版本后已封装到JAR包中 MatrixToImageWriter.writeToPath(bm, format, path); System.out.println("输出成功!"); } }