網站首頁 編程語言 正文
一.zxing是什么?
zxing是google推出的一個開源的二維碼框架,可以實現使用手機的攝像頭完成二維碼的掃描和解碼
二.集成zxing框架
1. 將獲取的jar包復制到工程的app/libs目錄下,刷新,然后去添加依賴
2. 集成java源碼,將demo工程QrScan中app/src/main/java/目錄下包中的zxing和util復制到此工程對應的app/src/main/java的包下
3. 修改package包名,修改import路徑,修改類包名
4. 同步資源,復制資源目錄
drawable:btn_back.png? ? flash_off.png? ? flash_on.png
layout:復制activity_capture.xml,activity_scanner.xml,toolbar_scanner.xml
raw:全部復制
values:復制 / 替換其中的attrs.xml,ids.xml,colors.xml
5.修改工具欄框架包和ViewFinderView包路徑
6.打開開發權限,在清單文件中添加開發權限
<!--攝像機權限--> <uses-permission android:name="android.permission.CAMERA" /> <!--手機震動權限--> <uses-permission android:name="android.permission.VIBRATE" /> <!--讀取本地圖片權限--> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
7.最后運行一下工程,如果沒報錯的話就成功了
三.界面設計
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="掃描結果" 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" />
四.二維碼生成
創建類CreateUtil,并編寫createQRCode()方法來實現
public class CreateUtil {
//String codestring:要生成二維碼的字符串
// int width:二維碼圖片的寬度
// int height:二維碼圖片的高度
public static Bitmap createQRCode(String codestring,int width,int height){
try {
//首先判斷參數的合法性,要求字符串內容不能為空或圖片長寬必須大于0
if (TextUtils.isEmpty(codestring)||width<=0||height<=0){
return null;
}
//設置二維碼的相關參數,生成BitMatrix(位矩陣)對象
Hashtable<EncodeHintType,String> hashtable=new Hashtable<>();
hashtable.put(EncodeHintType.CHARACTER_SET,"utf-8"); //設置字符轉碼格式
hashtable.put(EncodeHintType.ERROR_CORRECTION,"H"); //設置容錯級別
hashtable.put(EncodeHintType.MARGIN,"2"); //設置空白邊距
//encode需要拋出和處理異常
BitMatrix bitMatrix=new QRCodeWriter().encode(codestring, BarcodeFormat.QR_CODE,width,height,hashtable);
//再創建像素數組,并根據位矩陣為數組元素賦顏色值
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; //設置黑色色塊
}else{
pixel[h*width+w]=Color.WHITE; //設置白色色塊
}
}
}
//創建bitmap對象
//根據像素數組設置Bitmap每個像素點的顏色值,之后返回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中編寫代碼——生成二維碼
//點擊開始生成按鈕監聽事件
startBt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input=inputEt.getText().toString(); //獲取用戶輸入的字符串
//調用CreateUtil類生成二維碼后顯示在界面上
contentIv.setImageBitmap(CreateUtil.createQRCode(input,contentIv.getWidth(),contentIv.getHeight()));
}
});
五.二維碼掃描
MainActivity中編寫代碼
//開始掃描按鈕點擊事件監聽
startBt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scanQRCode();
}
});
//實現掃描二維碼的方法
private void scanQRCode() {
//申請相機權限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
return;
}
//申請文件(相冊)讀寫權限
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機制啟動zxing框架的CaptureActivity,請求返回結果
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);
//掃描結果回調
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:
//攝像頭權限申請
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//獲得授權
scanQRCode();
} else {
//被禁止授權
Toast.makeText(this, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
}
break;
case Constant.REQ_PERM_EXTERNAL_STORAGE:
//文件讀寫權限申請
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//獲得授權
scanQRCode();
} else {
//被禁止授權
Toast.makeText(this, "請至權限中心打開本應用的文件讀寫權限", Toast.LENGTH_LONG).show();
}
break;
}
}
}
到此,一個簡易的二維碼生成與掃描就完成了
附:Android使用Zxing識別圖片多個二維碼
android通過zxing可識別bitmap多個二維碼,具體使用如下
1.首先build文件添加依賴
implementation 'com.google.zxing:core:3.3.3'
2.使用 QRCodeMultiReader 來解析 Bitmap獲取Result數組(二維碼圖片地址集合)
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);
// 將圖片轉換成二進制圖片
BinaryBitmap binaryBitmap = new BinaryBitmap(new
GlobalHistogramBinarizer(source));
QRCodeMultiReader reader = new QRCodeMultiReader();// 初始化解析對象
try {
result = reader.decodeMultiple(binaryBitmap,
CodeHintsUtils.getDefaultDecodeHints());// 解析獲取一個Result數組
} catch (NotFoundException e) {
e.printStackTrace();
}
}
return result;
}
3.通過獲取數組下的Result對象,result.getText();//得到二維碼信息地址
總結
原文鏈接:https://blog.csdn.net/Ai1114/article/details/125915688
相關推薦
- 2023-10-31 SpringBoot手動獲取實例
- 2021-12-11 關于docker容器部署redis步驟介紹_docker
- 2022-01-29 fastadmin自定義按鈕url,去掉默認的ids參數
- 2022-01-29 composer global require “fxp/composer-asset-plugin
- 2021-12-14 go調用shell命令兩種方式實現(有無返回值)_Golang
- 2023-01-15 Android傳感器使用實例介紹_Android
- 2023-03-25 詳解Python中命令行參數argparse的常用命令_python
- 2022-12-24 python的open函數常見用法_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支