欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android中二維碼的掃描和生成(使用zxing庫)

 更新時間:2022年09月02日 16:37:36   作者:是小A  
ZXing是一個開放源碼的,用Java實(shí)現(xiàn)的多種格式的1D/2D條碼圖像處理庫,它包含了聯(lián)系到其他語言的端口,下面這篇文章主要給大家介紹了關(guān)于Android中二維碼掃描和生成的相關(guān)資料,主要使用的zxing庫,需要的朋友可以參考下

一.zxing是什么?

zxing是google推出的一個開源的二維碼框架,可以實(shí)現(xiàn)使用手機(jī)的攝像頭完成二維碼的掃描和解碼

二.集成zxing框架

1. 將獲取的jar包復(fù)制到工程的app/libs目錄下,刷新,然后去添加依賴

2. 集成java源碼,將demo工程QrScan中app/src/main/java/目錄下包中的zxing和util復(fù)制到此工程對應(yīng)的app/src/main/java的包下

3. 修改package包名,修改import路徑,修改類包名

4. 同步資源,復(fù)制資源目錄

drawable:btn_back.png    flash_off.png    flash_on.png

layout:復(fù)制activity_capture.xml,activity_scanner.xml,toolbar_scanner.xml

raw:全部復(fù)制

values:復(fù)制 / 替換其中的attrs.xml,ids.xml,colors.xml

5.修改工具欄框架包和ViewFinderView包路徑

6.打開開發(fā)權(quán)限,在清單文件中添加開發(fā)權(quán)限

    <!--攝像機(jī)權(quán)限-->
    <uses-permission android:name="android.permission.CAMERA" />
    <!--手機(jī)震動權(quán)限-->
    <uses-permission android:name="android.permission.VIBRATE" />
    <!--讀取本地圖片權(quán)限-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

7.最后運(yùn)行一下工程,如果沒報錯的話就成功了

三.界面設(shè)計

activity_main.xml代碼如下:

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">
 
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />
 
</com.google.android.material.appbar.AppBarLayout>
 
<include layout="@layout/content_main" />
 
<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    app:srcCompat="@android:drawable/ic_dialog_email" />

content.xml代碼如下:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="48dp"
    android:hint="掃描結(jié)果"
    android:textSize="24sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/myScanButton"
    app:layout_constraintVertical_bias="0.0" />
 
<EditText
    android:id="@+id/myEditText"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:ems="10"
    android:hint="輸入要生成二維碼的字符"
    android:inputType="textPersonName"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
 
<Button
    android:id="@+id/myCreateButton"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="開始生成"
    android:textSize="18sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/myEditText" />
 
<ImageView
    android:id="@+id/myImageView"
    android:layout_width="202dp"
    android:layout_height="196dp"
    android:layout_marginTop="64dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/myCreateButton"
    app:srcCompat="@android:drawable/screen_background_light_transparent" />
 
<Button
    android:id="@+id/myScanButton"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="36dp"
    android:text="開始掃描"
    android:textSize="18sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/myImageView" />

四.二維碼生成

創(chuàng)建類CreateUtil,并編寫createQRCode()方法來實(shí)現(xiàn)

public class CreateUtil {
    //String codestring:要生成二維碼的字符串
    // int width:二維碼圖片的寬度
    // int height:二維碼圖片的高度
    public static Bitmap createQRCode(String codestring,int width,int height){
        try {
            //首先判斷參數(shù)的合法性,要求字符串內(nèi)容不能為空或圖片長寬必須大于0
            if (TextUtils.isEmpty(codestring)||width<=0||height<=0){
                return null;
            }
            //設(shè)置二維碼的相關(guān)參數(shù),生成BitMatrix(位矩陣)對象
            Hashtable<EncodeHintType,String> hashtable=new Hashtable<>();
            hashtable.put(EncodeHintType.CHARACTER_SET,"utf-8");  //設(shè)置字符轉(zhuǎn)碼格式
            hashtable.put(EncodeHintType.ERROR_CORRECTION,"H");   //設(shè)置容錯級別
            hashtable.put(EncodeHintType.MARGIN,"2"); //設(shè)置空白邊距
            //encode需要拋出和處理異常
            BitMatrix bitMatrix=new QRCodeWriter().encode(codestring, BarcodeFormat.QR_CODE,width,height,hashtable);
            //再創(chuàng)建像素數(shù)組,并根據(jù)位矩陣為數(shù)組元素賦顏色值
            int[] pixel=new int[width*width];
            for (int h=0;h<height;h++){
                for (int w=0;w<width;w++){
                    if (bitMatrix.get(w,h)){
                        pixel[h*width+w]= Color.BLACK;  //設(shè)置黑色色塊
                    }else{
                        pixel[h*width+w]=Color.WHITE;  //設(shè)置白色色塊
                    }
                }
            }
            //創(chuàng)建bitmap對象
            //根據(jù)像素數(shù)組設(shè)置Bitmap每個像素點(diǎn)的顏色值,之后返回Bitmap對象
            Bitmap qrcodemap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
            qrcodemap.setPixels(pixel,0,width,0,0,width,height);
            return qrcodemap;
        }catch (WriterException e){
            return null;
        }
    }
}

在MainActivity中編寫代碼——生成二維碼

//點(diǎn)擊開始生成按鈕監(jiān)聽事件
startBt1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String input=inputEt.getText().toString();  //獲取用戶輸入的字符串  
        //調(diào)用CreateUtil類生成二維碼后顯示在界面上
        contentIv.setImageBitmap(CreateUtil.createQRCode(input,contentIv.getWidth(),contentIv.getHeight()));
    }
});

五.二維碼掃描

MainActivity中編寫代碼

        //開始掃描按鈕點(diǎn)擊事件監(jiān)聽
        startBt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanQRCode();
            }
        });
    
 
 
 
    //實(shí)現(xiàn)掃描二維碼的方法
    private void scanQRCode() {
        //申請相機(jī)權(quán)限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        //申請文件(相冊)讀寫權(quán)限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        //二維碼掃碼
        //然后通過Intent機(jī)制啟動zxing框架的CaptureActivity,請求返回結(jié)果
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //掃描結(jié)果回調(diào)
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //將掃描出的信息顯示出來
            resultTv.setText(scanResult);
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case Constant.REQ_PERM_CAMERA:
                //攝像頭權(quán)限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //獲得授權(quán)
                    scanQRCode();
                } else {
                    //被禁止授權(quán)
                    Toast.makeText(this, "請至權(quán)限中心打開本應(yīng)用的相機(jī)訪問權(quán)限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                //文件讀寫權(quán)限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //獲得授權(quán)
                    scanQRCode();
                } else {
                    //被禁止授權(quán)
                    Toast.makeText(this, "請至權(quán)限中心打開本應(yīng)用的文件讀寫權(quán)限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
}

到此,一個簡易的二維碼生成與掃描就完成了

附:Android使用Zxing識別圖片多個二維碼

android通過zxing可識別bitmap多個二維碼,具體使用如下

1.首先build文件添加依賴

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

2.使用 QRCodeMultiReader 來解析 Bitmap獲取Result數(shù)組(二維碼圖片地址集合)

 public static com.google.zxing.Result[] decodeQR(Bitmap srcBitmap) {
        com.google.zxing.Result[] result = null;
        if (srcBitmap != null) {
            int width = srcBitmap.getWidth();
            int height = srcBitmap.getHeight();
            int[] pixels = new int[width * height];
            srcBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
            // 新建一個RGBLuminanceSource對象
            RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
            // 將圖片轉(zhuǎn)換成二進(jìn)制圖片
            BinaryBitmap binaryBitmap = new BinaryBitmap(new    
            GlobalHistogramBinarizer(source));
            QRCodeMultiReader reader = new QRCodeMultiReader();// 初始化解析對象
            try {
                result = reader.decodeMultiple(binaryBitmap, 
                CodeHintsUtils.getDefaultDecodeHints());// 解析獲取一個Result數(shù)組
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

3.通過獲取數(shù)組下的Result對象,result.getText();//得到二維碼信息地址

總結(jié)

到此這篇關(guān)于Android中二維碼掃描和生成(使用zxing庫)的文章就介紹到這了,更多相關(guān)Android二維碼掃描生成內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論