带logo的二维码

生成一个带logo的二维码

现在的app基本都会带有生成二维码的功能,为了提现高大上,往往会在二维码的中间加上一个有个性的logo(公司的标志或者app应用的icon).但是这个高大上的需求其实非常容易实现,下面就直接上代码

/**
     * 生成二维码
     * 
     * @param string
     *            二维码中包含的文本信息
     * @param mBitmap
     *            logo图片
     * @param format
     *            编码格式BarcodeFormat.QR_CODE
     * @return Bitmap 位图
     * @throws WriterException
     */
    public Bitmap createCode(String string, Bitmap mBitmap, BarcodeFormat format)
            throws WriterException {
        //往往对logo的大小有要求,所以需要经过压缩处理,压缩比例可以根据自己的需要进行调整,当然,最终的结果是不影响识别率
        Matrix m = new Matrix();
        float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
        float sy = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getHeight();
        m.setScale(sx, sy);// 设置缩放信息
        // 将logo图片按martix设置的信息缩放
        mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
                mBitmap.getHeight(), m, false);
        QRCodeWriter writer = new QRCodeWriter();
        Hashtable<EncodeHintType, Object> hst = new Hashtable<EncodeHintType, Object>();
        hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 设置字符编码
        hst.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //容错率设置高一点
        BitMatrix matrix = writer.encode(string, format, 600, 600, hst);// 生成二维码矩阵信息
        int width = matrix.getWidth();// 矩阵高度
        int height = matrix.getHeight();// 矩阵宽度
        //提前拿到二维码的中心点坐标,方便后面logo位置的判断
        int halfW = width / 2;
        int halfH = height / 2;
        int[] pixels = new int[width * height];// 定义数组长度为矩阵高度*矩阵宽度,用于记录矩阵中像素信息
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
                        && y > halfH - IMAGE_HALFWIDTH
                        && y < halfH + IMAGE_HALFWIDTH) {// 该位置用于存放图片信息
                    // 记录图片每个像素信息
                    pixels[y * width + x] = mBitmap.getPixel(x - halfW
                            + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
                } else {
                    if (matrix.get(x, y)) {// 如果有黑块点,记录信息
                        pixels[y * width + x] = 0xff000000;// 记录黑块信息
                    }
                }

            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // 通过像素数组生成bitmap
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;

    }

不要忘记加入jar包QRCodeCore.jar.好了,生成带logo的二维码就是这么简单

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值