使用ZXing库生成二维码

  1. 首先在库依赖中添加 com.google.zxing:core:3.2.1
  2. /** 
  3.      * 生成二维码 
  4.      * @param string 二维码中包含的文本信息 
  5.      * @param mBitmap logo图片 
  6.      * @param format  编码格式 
  7.      * @return Bitmap 位图 
  8.      * @throws WriterException 
  9.      */  
  10.     public Bitmap createCode(String string,Bitmap mBitmap, BarcodeFormat format)  
  11.             throws WriterException {  
  12.         Matrix m = new Matrix();  
  13.         float sx = (float2 * IMAGE_HALFWIDTH / mBitmap.getWidth();  
  14.         float sy = (float2 * IMAGE_HALFWIDTH  
  15.                 / mBitmap.getHeight();  
  16.         m.setScale(sx, sy);//设置缩放信息  
  17.         //将logo图片按martix设置的信息缩放  
  18.         mBitmap = Bitmap.createBitmap(mBitmap, 00,  
  19.                 mBitmap.getWidth(), mBitmap.getHeight(), m, false);  
  20.         MultiFormatWriter writer = new MultiFormatWriter();  
  21.         Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();  
  22.         hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");//设置字符编码  
  23.         BitMatrix matrix = writer.encode(string, format, 400400, hst);//生成二维码矩阵信息  
  24.         int width = matrix.getWidth();//矩阵高度  
  25.         int height = matrix.getHeight();//矩阵宽度  
  26.         int halfW = width / 2;  
  27.         int halfH = height / 2;  
  28.         int[] pixels = new int[width * height];//定义数组长度为矩阵高度*矩阵宽度,用于记录矩阵中像素信息  
  29.         for (int y = 0; y < height; y++) {//从行开始迭代矩阵  
  30.             for (int x = 0; x < width; x++) {//迭代列  
  31.                 if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH  
  32.                         && y > halfH - IMAGE_HALFWIDTH  
  33.                         && y < halfH + IMAGE_HALFWIDTH) {//该位置用于存放图片信息  
  34. //记录图片每个像素信息  
  35.                     pixels[y * width + x] = mBitmap.getPixel(x - halfW  
  36.                             + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);                } else {  
  37.                     if (matrix.get(x, y)) {//如果有黑块点,记录信息  
  38.                         pixels[y * width + x] = 0xff000000;//记录黑块信息  
  39.                     }  
  40.                 }  
  41.   
  42.             }  
  43.         }  
  44.         Bitmap bitmap = Bitmap.createBitmap(width, height,  
  45.                 Bitmap.Config.ARGB_8888);  
  46.         // 通过像素数组生成bitmap  
  47.         bitmap.setPixels(pixels, 0, width, 00, width, height);  
  48.         return bitmap;  
  49.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优雅的心情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值