android 分享二维码图片到微信QQ(url地址字符串生成二维码图片、分享二维码图片到微信QQ)

主要用到的功能

1、url地址字符串生成二维码图片
2、分享二维码图片到微信QQ

所需的依赖包

implementation 'com.google.zxing:core:3.0.1'

代码

1、将URL转成二维码图片

 	/**
     * 1、将字符串生成二维码图片
     *
     * @param str
     * @return
     */
    public Bitmap Create2DCode(String str) {
        //生成二维矩阵,编码时要指定大小,
        //不要生成了图片以后再进行缩放,以防模糊导致识别失败
        try {
            BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 200, 200);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            Log.d("WY+", "宽高为:" + width + "|" + height);
            //  二维矩阵转为一维像素数组(一直横着排)
            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.ARGB_8888);
            // 通过像素数组生成bitmap, 具体参考api
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
//        } catch (WriterException e) {
//            e.printStackTrace();
        } catch (com.google.zxing.WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

2、分享二维码图片到微信QQ等已安装的app

/**
     * 分享图片(直接将bitamp转换为Uri)
     *
     * @param bitmap
     */
    private void shareImg(Bitmap bitmap) {
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("image/*");//设置分享内容的类型
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent = Intent.createChooser(intent, "分享");
        startActivity(intent);
    }

调用

shareImg(Create2DCode(url));

分享文字

/**
     * Android原生分享功能
     *
     * @param appName:要分享的应用程序名称
     */
    private void share(String appName) {
        Intent share_intent = new Intent();
        share_intent.setAction(Intent.ACTION_SEND);
        share_intent.setType("text/plain");
        share_intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
        share_intent.putExtra(Intent.EXTRA_TEXT, "推荐您使用一款软件:" + appName);
        share_intent = Intent.createChooser(share_intent, "分享");
        startActivity(share_intent);
    }

猜你喜欢

转载自blog.csdn.net/wy313622821/article/details/107320868