生成二维码以及生成带头像标示的二维码

来源:互联网 发布:vb宽度高度 编辑:程序博客网 时间:2024/06/06 04:29
/** * 用字符串生成二维码 * * @param text * @return * @throws WriterException */public static Bitmap create2DCode(String text) {    //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败    Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    hints.put(EncodeHintType.MARGIN, 0);    BitMatrix matrix = null;    try {        matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 400, 400, hints);    } catch (WriterException e) {        e.printStackTrace();    }    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;            } else {                pixels[y * width + x] = 0xffffffff;            }        }    }    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);    //通过像素数组生成bitmap,具体参考api    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);    return bitmap;

}

/**     * 生成带图片的二维码     *     * @param qr     * @param rid     */    public static void createQRCodeBitmapWithPortrait(Bitmap qr, int rid, int width) {        Bitmap portrait = BitmapFactory.decodeResource(MyApp.getInstance().getResources(), rid);        // 头像图片的大小        int strokeWidth = 8;//边框宽度        int portrait_W = portrait.getWidth();        int portrait_H = portrait.getHeight();        if (portrait_W > width) {            double param = ((double) portrait_W) / ((double) width);            portrait_H = ((int) (((double) portrait_H) / param));            portrait_W = width;            portrait = Bitmap.createScaledBitmap(portrait, portrait_W, portrait_H, true);        }        // 设置头像要显示的位置,即居中显示        int left = (qr.getWidth() - portrait_W) / 2;        int top = (qr.getHeight() - portrait_H) / 2;        int right = left + portrait_W;        int bottom = top + portrait_H;        Rect rect1 = new Rect(left, top, right, bottom);        // 取得qr二维码图片上的画笔,即要在二维码图片上绘制我们的头像        Canvas canvas = new Canvas(qr);        // 设置我们要绘制的范围大小,也就是头像的大小范围        Rect rect2 = new Rect(0, 0, portrait_W, portrait_H);        Paint paint = new Paint();        paint.setColor(MyApp.getInstance().getResources().getColor(R.color.main_blue));        paint.setStrokeWidth(strokeWidth);        Rect side = new Rect(left, top, right, bottom);        // 开始绘制        canvas.drawBitmap(portrait, rect2, rect1, null);    }
使用方法:
Bitmap bmp = Tools.create2DCode("生成二维码的内容");Tools.createQRCodeBitmapWithPortrait(bmp, R.mipmap.logo, bmp.getWidth() / 6);iv_two_pic.setImageBitmap(bmp);结果查看:


0 0