博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉点击跳转到网站
前言:自己遇到了这样一个需求,所以把这个记录一下,后期再用到,直接拿来用就行了。
1.写相册按钮的监听事件,用ACTION_GET_CONTENT获取所有本地的图片。
Intent.ACTION_GET_CONTENT
必须设置setType(“image/*”)表示返回的数据类型,否则会报,android.content.ActivityNotFoundException异常。
//打开相册
iv_capture_photo=findViewById(R.id.iv_capture_photo);
iv_capture_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_CODE_SCAN);
}
});
2.用onActivityResult()
将获取的返回数据交给显示的页面去处理
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode==RESULT_OK){
switch (requestCode){
case REQUEST_CODE_SCAN:
handleAlbumPic(data); //方法
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
3.创建handleAlbumPic()
方法,处理选择的图片,将获取的值,传给扫描之后显示的界面
/**
* 处理选择的图片
* @param data
*/
private void handleAlbumPic(Intent data) {
final Uri uri = data.getData();
Result result =scanningImage(uri); //scanningImage()方法,对获取的图片进行扫描
if (result!=null){
Toast.makeText(this, "扫描成功", Toast.LENGTH_SHORT).show();
//使用返回信息
Intent intent = new Intent(this, DevCodeAccessActivity.class);
Bundle bundle = new Bundle();
bundle.putString("devcode", String.valueOf(result));
intent.putExtras(bundle);
startActivity(intent, bundle);
finish();
}else {
Toast.makeText(this, "识别失败", Toast.LENGTH_SHORT).show();
}
}
4.创建scanningImage()
方法,去获取图片进行扫描。
/**
* 对获取的图片进行扫描
* @param uri
* @return
*/
private Result scanningImage(Uri uri) {
if (uri == null) {
return null;
}
Hashtable<DecodeHintType, String> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码
scanBitmap=BitmapUtil.decodeUri(this,uri,500,500);
RGBLuminacnce source=new RGBLuminacnce(scanBitmap);
BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
try {
return reader.decode(bitmap1, hints);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
return null;
}
该方法中RGBLuminacnce和BitmapUtil两个实体类,没在本文中写出,需要的可以私信我,以上仅作为记录学习,总结!
有任何问题可以在评论区指出,一起学习,共同进步,奔向自己的未来!