android 将字符串生成二维码 您所在的位置:网站首页 文本生成二维码 android 将字符串生成二维码

android 将字符串生成二维码

2024-06-03 05:21| 来源: 网络整理| 查看: 265

之前项目有个二维码打印的需求,需要通过字符串生成一个二维码图片(bitmap)

直接上代码, 简单好用

需要注意的是,这个代码依赖于com.google.zxing包

public static Bitmap Create2DCode(String str) { //生成二维矩阵,编码时要指定大小, //不要生成了图片以后再进行缩放,以防模糊导致识别失败 try { BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 240, 240); int width = matrix.getWidth(); int height = matrix.getHeight(); // 二维矩阵转为一维像素数组(一直横着排) int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // 通过像素数组生成bitmap, 具体参考api bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (WriterException e) { e.printStackTrace(); } return null; }

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有