java中生成二维码的方法基本有两种,QrcodeZxing两种方式。
  但是Qrcode存储的数据有限,而且调起来比较麻烦,生成出来的二维码不好看,有点乱。
  而Zxinggoogle公司的,转换的算法果然牛掰,直接就傻瓜式用就行了,生成的二维码也比较好看,看起来比较规范。

方法如下:

1、引入依赖
<dependency>
   <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.0.0</version>
</dependency>
2、工具类

  我又找到去白边的方法,也加到了这里边,可以查看下边的testEncode方法,通过传入deleteWhitetrue时,可实现去白边。

package springboot.xjweb.utils.zxing;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
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.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import static com.google.zxing.client.j2se.MatrixToImageConfig.BLACK;
import static com.google.zxing.client.j2se.MatrixToImageConfig.WHITE;
/**
 * Created by lingsf on 2019/4/29.
 */
public class ZxingOrCodeUtils {
    /**
     * 生成二维码图片
     * @param content 二维码中的数据
     * @param filePath 生成二维码的根路径   fileName文件名
     * @param deleteWhite 默认二维码边上是带有白边的,传true时会去掉白边
     */
    public static void testEncode(String content,String filePath,String fileName,boolean deleteWhite) throws WriterException, IOException {

        int width = 200; // 图像宽度
        int height = 200; // 图像高度
        String format = "png";// 图像类型
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        if(deleteWhite){ //删除白边
            BufferedImage image = deleteWhite(bitMatrix); //去白边的话加这一行
            File outputfile = new File(filePath+fileName);
            ImageIO.write(image, "png", outputfile);
            return;
        }

        Path path = FileSystems.getDefault().getPath(filePath, fileName);
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
        System.out.println("输出成功.");
    }

    /**
     * 生成二维码图片内容
     * @param filePath  文件的绝对路径 例如:"D://zxing.png";
     */
    public static void testDecode(String filePath) {
        BufferedImage image;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            System.out.println(result.getText());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
    }

    //去白边的话,调用这个方法
    private static BufferedImage  deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }

        int width = resMatrix.getWidth();
        int height = resMatrix.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, resMatrix.get(x, y) ? BLACK
                        : WHITE);
            }
        }
        return image;
    }
    public static void main(String[] args){
    //1、去白边的方法例子
//        String fileName = "zxing.png";
//        String content = "西秀区农村土地承包经营权证\n" +
//                "权证编码:398881111222211J\n" +
//                "发包方名称:轿子山镇大进村民委员会\n" +
//                "承包方代表:杨井岗\n" +
//                "确权总面积:12.33亩\n" +
//                "地块总数:13块";//内容信息
//        try {
//            testEncode(content,"D://",fileName,true);
//        } catch (WriterException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
 //2、简单的生成二维码例子
        testDecode("D://zxing.png");
    }
}

3、实际应用例子

  下面例子中有两个地方要注意一下:

  1. ImageIO.setUseCache(false); 这句话最好加上,如果不加,默认是先将文件生成到,项目运行的缓存中,比如你用java -jar运行,一般情况下你会放在c盘,如果你的c盘没有权限写入东西,那完了,妥妥的抛异常。加上没毛病。。。
  2. getContent方法里,字符串中我加了\n,你没有看错,就是方便二维码读出的数据中,能够换行,如果不加,都在一行上,比较难看。
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import springboot.xjweb.model.CbfQrImgeData;
import springboot.xjweb.service.dubboService.CbfDubboService;
import springboot.xjweb.utils.zxing.ZxingOrCodeUtils;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
 * google的zxing生成二维码
 */
@Controller
public class ImageController {
    @Value("${spring.file.uploadpath}")
    public String filePath;

    @Autowired
    private CbfDubboService cbfDubboService;

    // 测试
    @RequestMapping(value = "/ndrestful/api/getQrCode", method = RequestMethod.GET)
    public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String qzbm = request.getParameter("qzbm");
        String content =getContent(qzbm);
        String fileName = "/"+qzbm+".png";
        try {
        	// 1、生成二维码到服务器路径下
            ZxingOrCodeUtils.testEncode(content,filePath,fileName,true);
            // 2、读取二维码
            BufferedImage image = ImageIO.read(new File(filePath+fileName));
            //这句话加上,避免将文件生成到缓存里,有时候会生成失败,造成接口异常
            ImageIO.setUseCache(false); 
            //3、通过write方法将图像从内存中写到页面上。
            ImageIO.write(image , "PNG", response.getOutputStream()); 
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
    //根据权证编码获取数据,拼接后返回,如果获取失败,则返回错误信息
    public String getContent(String qzbm){
        if(qzbm == null){
            return "\n未传入权证编码,查询失败";
        }
        CbfQrImgeData cbfQrImgeData = cbfDubboService.selectQrImageDataFromQzbm(qzbm);
        if(cbfQrImgeData != null){
            return  "\n农村土地承包经营权证\n" +
                "权证编码:"+qzbm+"\n" +
                "发包方:"+cbfQrImgeData.getFbfmc()+"\n" +
                "承包方:"+cbfQrImgeData.getCbfmc()+"\n" +
                "总面积:"+cbfQrImgeData.getHtzmj()+"亩\n" +
                "地块总数:"+cbfQrImgeData.getCbdkzs()+"块\n";//内容信息
        }else{
            return "\n未匹配到相关数据";
        }

    }
}

GitHub 加速计划 / zx / zxing
32.53 K
9.31 K
下载
ZXing ("Zebra Crossing") barcode scanning library for Java, Android
最近提交(Master分支:2 个月前 )
8944e607 2 个月前
6ea3726b Bumps `spring.version` from 6.1.5 to 6.1.8. Updates `org.springframework:spring-test` from 6.1.5 to 6.1.8 - [Release notes](https://github.com/spring-projects/spring-framework/releases) - [Commits](https://github.com/spring-projects/spring-framework/compare/v6.1.5...v6.1.8) Updates `org.springframework:spring-web` from 6.1.5 to 6.1.8 - [Release notes](https://github.com/spring-projects/spring-framework/releases) - [Commits](https://github.com/spring-projects/spring-framework/compare/v6.1.5...v6.1.8) --- updated-dependencies: - dependency-name: org.springframework:spring-test dependency-type: direct:development update-type: version-update:semver-patch - dependency-name: org.springframework:spring-web dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Sean Owen <srowen@gmail.com> 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐