android studio zxing 生成和扫描二维码

加依赖

 	implementation 'com.journeyapps:zxing-android-embedded:3.6.0'  //生成
    implementation 'com.google.zxing:javase:3.0.0'

MainActivity

package wlt.com.hyjj;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView jieguo;
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        init();
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.arg1==101){
                imageView.setImageBitmap((Bitmap) msg.obj);
            }
            return true;
        }
    });
    public  void init(){
        jieguo=(TextView)this.findViewById(R.id.jieguo);
        imageView=(ImageView)this.findViewById(R.id.imgscar);
    }

   

    /**
     * 生成二维码1
     */

    public static Bitmap createBitmap(String str){
        Bitmap bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 400, 400);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitmap = barcodeEncoder.createBitmap(result);
        } catch (WriterException e){
            e.printStackTrace();
        } catch (IllegalArgumentException iae){
            return null;
        }
        return bitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if (requestCode == 101) {
            System.out.print("=====101=======");
            IntentResult scanResult = IntentIntegrator.parseActivityResult(resultCode, data);
            final String qrContent = scanResult.getContents();
            Toast.makeText(MainActivity.this, "扫描结果:" + qrContent, Toast.LENGTH_SHORT).show();
            jieguo.setText(qrContent);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.item,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item) {
        switch (item.getItemId()){

            case R.id.bdtp:
                Bitmap bitmap =zxing_Utlis.QRCode.createQRCode("https://blog.csdn.net/qq_38218307");
                Message mess=new Message();
                mess.arg1=101;
                mess.obj=bitmap;
                handler.sendMessage(mess);
                if (bitmap!=null){
                    Toast.makeText(MainActivity.this,"成功",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.dtp:
                Bitmap bit=  BitmapFactory.decodeResource(getResources(),R.drawable.s);
                Bitmap bitmaps=  zxing_Utlis.QRCode.createQRCodeWithLogo("https://blog.csdn.net/qq_38218307",bit);
                Message messs=new Message();
                messs.arg1=101;
                messs.obj=bitmaps;
                handler.sendMessage(messs);
                if (bitmaps!=null){
                    Toast.makeText(MainActivity.this,"成功",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.sb:
                //打开扫描界面
                IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);
                intentIntegrator.setOrientationLocked(false);
                intentIntegrator.setCaptureActivity(ScanActivity.class); // 设置自定义的activity是QRActivity 自定义扫描界面
                intentIntegrator.setRequestCode(101);
                intentIntegrator.initiateScan();

                break;
            case R.id.scsb:
                Intent intent=new Intent(MainActivity.this,Uri_Utlis.class);
                startActivity(intent);

                break;

                default:

        }
        return true;
    }
}

content_main布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    >

    <ImageView
        android:id="@+id/imgscar"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/ic_launcher_background" />

    <LinearLayout
        android:layout_marginTop="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        />

    <TextView
        android:textSize="20dp"
        android:layout_marginTop="20dp"
        android:id="@+id/jieguo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello 这里是结果!"

        />

</LinearLayout>

menu


<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <item android:id="@+id/bdtp" android:title="不带图片生成" />
    <item android:id="@+id/dtp" android:title="带图片生成" />
    <item android:id="@+id/sb" android:title="识别" />
    <item android:id="@+id/scsb" android:title="相册识别" />
</menu>

zxing_Utlis

	 下面这个方法 我在网上搬得 砖 改了好多次 原地址找不到了 我贴上 他们的博客  找不到了  。。

https://blog.csdn.net/wxb141001yxx/article/details/80786680

https://blog.csdn.net/lc547913923/article/details/100022424

package wlt.com.hyjj;

import android.graphics.Bitmap;
import android.graphics.Matrix;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

public class zxing_Utlis {

    public static class QRCode {
        /**
         * 生成二维码,默认大小为500*500
         * @param url 需要生成二维码的网址,也可以是文字
         * @param //xize 需要生成二维码的大小()
         * @return bitmap
         */
        public static Bitmap createQRCode(String url) {
            return createQRCode(url, 500);
        }
        public static Bitmap createQRCode(String url, int size) {
            try {
                Hashtable<EncodeHintType, String> hints = new Hashtable<>();
                hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
                BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                        BarcodeFormat.QR_CODE, size, size, hints);
                int[] pixels = new int[size * size];
                for (int y = 0; y < size; y++) {
                    for (int x = 0; x < size; x++) {
                        if (bitMatrix.get(x, y)) {
                            pixels[y * size + x] = 0xff000000;
                        } else {
                            pixels[y * size + x] = 0xffffffff;
                        }

                    }
                }
                Bitmap bitmap = Bitmap.createBitmap(size, size,
                        Bitmap.Config.ARGB_8888);
                bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
                return bitmap;
            } catch (WriterException e) {
                e.printStackTrace();
                return null;
            }
        }

        /**
         * 生成带logo的二维码,默认二维码的大小为500,logo为二维码的1/5
         * @param url 需要生成二维码的文字、网址等
         * @param size 需要生成二维码的大小()
         * @param mBitmap logo文件
         * @return bitmap
         */
        private static int IMAGE_HALFWIDTH = 50;//宽度值,影响中间图片大小
        public static Bitmap createQRCodeWithLogo(String url, Bitmap mBitmap) {
            return createQRCodeWithLogo(url,500,mBitmap);
        }
        public static Bitmap createQRCodeWithLogo(String url, int size, Bitmap mBitmap) {
            try {
                IMAGE_HALFWIDTH = size/10;
                Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
                hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
                /*
                 * 设置容错级别,默认为ErrorCorrectionLevel.L
                 * 因为中间加入logo所以建议你把容错级别调至H,否则可能会出现识别不了
                 */
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                        BarcodeFormat.QR_CODE, size, size, hints);
                int width = bitMatrix.getWidth();//矩阵高度
                int height = bitMatrix.getHeight();//矩阵宽度
                int halfW = width / 2;
                int halfH = height / 2;

                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);

                int[] pixels = new int[size * size];
                for (int y = 0; y < size; y++) {
                    for (int x = 0; x < size; 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 (bitMatrix.get(x, y)) {
                                pixels[y * size + x] = 0xff000000;
                            } else {
                                pixels[y * size + x] = 0xffffffff;
                            }
                        }
                    }
                }
                Bitmap bitmap = Bitmap.createBitmap(size, size,
                        Bitmap.Config.ARGB_8888);
                bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
                return bitmap;
            } catch (WriterException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}

Uri_Utlis

package wlt.com.hyjj;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;


public class Uri_Utlis  extends Activity {
    private Button btn;
    private TextView textView;

    private String photo_path;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xiangcetuo);

        btn=(Button)this.findViewById(R.id.xiangcestuo);
        textView=(TextView)this.findViewById(R.id.tvjgtuo);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                startActivityForResult(intent, 101);
            }
        });
    }

    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage( Message msg) {

            if (msg.what==1){
                String str=(String)msg.obj;
                textView.setText("识别结果为"+str);
            }if (msg.what==2){
                String str=(String)msg.obj;
                textView.setText("识别结果为"+str);
            }

            return true;
        }
    });
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
            System.out.print("===========onActivityResult===========");
        if (requestCode==101){
            System.out.print("===========101===========");
            Uri uri = data.getData();
            System.out.println(uri.getPath());
            ContentResolver cr = this.getContentResolver();

          try {
                Bitmap  bmp = MediaStore.Images.Media.getBitmap(cr,uri);
             final Drawable drawable =new BitmapDrawable(bmp);
              new Thread(new Runnable() {
                  @Override
                  public void run() {
                     String result= getStringFromQRCode(drawable);
                      System.out.print("===========result==========="+result);
                      if (result != null) {
                          Message m = handler.obtainMessage();
                          m.what = 1;
                          m.obj =result;
                          handler.sendMessage(m);
                      } else {
                          Message m = handler.obtainMessage();
                          m.what = 2;
                          m.obj = "很遗憾!@!!@";
                          handler.sendMessage(m);
                      }

                  }
              }).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 解析
     * @return
     */
    public static String getStringFromQRCode(Drawable drawable) {
        String httpString = null;
        Bitmap bmp = drawableToBitmap(drawable);
        byte[] data =getYUV420sp(bmp.getWidth(), bmp.getHeight(), bmp);
        // 处理
        try {
            Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
           hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
            PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data,
                    bmp.getWidth(),
                    bmp.getHeight(),
                    0, 0,
                    bmp.getWidth(),
                    bmp.getHeight(),
                    false);
            BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
            QRCodeReader reader2= new QRCodeReader();
            Result result = reader2.decode(bitmap1, hints);

            httpString = result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }

        bmp.recycle();
        bmp = null;
        return httpString;
    }

    /**
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = Bitmap.Config.ARGB_8888;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        // 白色底色   应对透明图
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        canvas.drawRect(0, 0, w, h, paint);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;

    }


    public static byte[] getYUV420sp(int inputWidth, int inputHeight,
                                     Bitmap scaled) {
        int[] argb = new int[inputWidth * inputHeight];

        scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight);

        byte[] yuv = new byte[inputWidth * inputHeight * 3 / 2];

        encodeYUV420SP(yuv, argb, inputWidth, inputHeight);

        scaled.recycle();

        return yuv;
    }
    private static void encodeYUV420SP(byte[] yuv420sp, int[] argb, int width,
                                       int height) {
        // 帧图片的像素大小
        final int frameSize = width * height;
        // ---YUV数据---
        int Y, U, V;
        // Y的index从0开始
        int yIndex = 0;
        // UV的index从frameSize开始
        int uvIndex = frameSize;

        // ---颜色数据---
//      int a, R, G, B;
        int R, G, B;
        //
        int argbIndex = 0;
        //

        // ---循环所有像素点,RGB转YUV---
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {

                // a is not used obviously
//              a = (argb[argbIndex] & 0xff000000) >> 24;
                R = (argb[argbIndex] & 0xff0000) >> 16;
                G = (argb[argbIndex] & 0xff00) >> 8;
                B = (argb[argbIndex] & 0xff);
                //
                argbIndex++;

                // well known RGB to YUV algorithm
                Y = ((66 * R + 129 * G + 25 * B + 128) >> 8) + 16;
                U = ((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128;
                V = ((112 * R - 94 * G - 18 * B + 128) >> 8) + 128;

                //
                Y = Math.max(0, Math.min(Y, 255));
                U = Math.max(0, Math.min(U, 255));
                V = Math.max(0, Math.min(V, 255));

                // NV21 has a plane of Y and interleaved planes of VU each
                // sampled by a factor of 2
                // meaning for every 4 Y pixels there are 1 V and 1 U. Note the
                // sampling is every other
                // pixel AND every other scanline.
                // ---Y---
                yuv420sp[yIndex++] = (byte) Y;

                // ---UV---
//              if ((j % 2 == 0) && (i % 2 == 0)) {
//
//
//
//                  yuv420sp[uvIndex++] = (byte) V;
//
//                  yuv420sp[uvIndex++] = (byte) U;
//              }
            }
        }
    }


}

以上的 zxing_Utlis 这个类是封装了生成带图片和不带图片的二维码 两个方法 Uri_Utlis activate getStringFromQRCode 这个方法是解析二维码 关键 方法已经贴上 整理 这几个方法花了很长时间 经过真机测试 没有问题

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页