第一阶段已经实现了,但是由于过于匆忙,导致实现bug过多,如识别优化利用外部类进行实现,内部也进行实现,相机功能与手机不匹配,每一次运行需打开储存权限,今天进行了优化,将代码简化,同时套用《第一行代码》的相机调用与相册调用的,进行修改。
实验阶段:将代码在新一个activity内进行书写,最后在进行移植,移植过程旭需注意manifist,包名等的条件。
以下为代码以及结果:
一:我的接口类:主要处理文字提取
public class Main {
String information = "";
public String qiuqiu(String address)
{
// 通用文字识别
String url = "https://api.textin.com/ai/service/v2/recognize";
// 请登录后前往 “工作台-账号设置-开发者信息” 查看 x-ti-app-id
// 示例代码中 x-ti-app-id 非真实数据
String appId = "d368dac2ac82d494a983b1baeafab48e";
// 请登录后前往 “工作台-账号设置-开发者信息” 查看 x-ti-secret-code
// 示例代码中 x-ti-secret-code 非真实数据
String secretCode = "84926c65950082820bf0385a1deab535";
BufferedReader in = null;
DataOutputStream out = null;
String result ="";
// System.out.println(1);
try {
byte[] imgData = readfile(address); // image
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("x-tixxxxxxxx-id", appId);//进行加密处理,可自己免费申请
conn.setRequestProperty("x-ti-xxxxxxxx", secretCode);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST"); // 设置请求方式
out = new DataOutputStream(conn.getOutputStream());
out.write(imgData);
out.flush();
out.close();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
// System.out.println(3);
while ((line = in.readLine()) != null) {
result += line;
}
// System.out.println(4);
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
// System.out.println(5);
String str = result;
String startStr = "text\":\"";
String endStr = "\"}";
// System.out.println("识别结束");
printSubstringsBetween(str, startStr, endStr);
//System.out.println("识别结束");
// System.out.println(6);
return information;
}
public static byte[] readfile(String path) {
String imgFile = path;
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public void printSubstringsBetween(String str, String startStr, String endStr) {
int startIndex = 0;
while (startIndex != -1) { // 循环直到找到所有符合条件的子字符串
startIndex = str.indexOf(startStr, startIndex); // 找到起始字符串的索引位置
if (startIndex != -1) {
int endIndex = str.indexOf(endStr, startIndex + startStr.length()); // 找到结束字符串的索引位置
if (endIndex != -1) {
String substring = str.substring(startIndex + startStr.length(), endIndex); // 获取符合条件的子字符串
System.out.println(substring); // 换行输出子字符串
information = information + substring + '\n';
startIndex = endIndex + endStr.length(); // 更新起始位置
} else {
break; // 如果没有找到结束字符串,则结束循环
}
} else {
break; // 如果没有找到起始字符串,则结束循环
}
}
}
二:MainActivity
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
public static final int CHOOSE_PHOTO = 2;
private ImageView picture;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePhoto = (Button) findViewById(R.id.take_photo);
Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
picture = (ImageView) findViewById(R.id.picture);
takePhoto.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
//用于存放拍下的照片
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if(outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if(Build.VERSION.SDK_INT >= 24){
//File对象转换为Uri标识对象
System.out.println("outputImage = " + outputImage);
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.launcher.photoshop.fileprovider", outputImage);
System.out.println("imageUri = " + imageUri);
}else{
//指定图片的输出地址
imageUri = Uri.fromFile(outputImage);
}
//隐式Intent,启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
chooseFromAlbum.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
openAlbum();
}
}
});
}
private void openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);
}
@SuppressLint("MissingSuperCall")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if( resultCode == RESULT_OK ){
try{
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
// Android 4.0 之后不能在主线程中请求HTTP请求
new Thread(new Runnable(){
@Override
public void run() {
Main main = new Main();
main.qiuqiu(String.valueOf("/storage/emulated/0/Android/data/com.example.photoshop/cache/output_image.jpg"));
}
}).start();
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
break;
case CHOOSE_PHOTO:
if(resultCode == RESULT_OK){
//判断版本型号
if(Build.VERSION.SDK_INT >= 19) {
//4.4以上版本
handleImageOnKitKat(data);
new Thread(new Runnable(){
@Override
public void run() {
Main main = new Main();
main.qiuqiu(String.valueOf("/storage/emulated/0/Android/data/com.example.photoshop/cache/output_image.jpg"));
}
}).start();
} else {
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}
@SuppressLint("MissingSuperCall")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
Toast.makeText(this, "You denide the permission", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if(DocumentsContract.isDocumentUri(this, uri)) {
//如果是document类型的uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())) {
Toast.makeText(this, "success01", Toast.LENGTH_SHORT).show();
String id = docId.split(":")[1];
String secletion = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, secletion);
} else if("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Toast.makeText(this, "success02", Toast.LENGTH_SHORT).show();
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if("content".equalsIgnoreCase(uri.getScheme())) {
Toast.makeText(this, "success03", Toast.LENGTH_SHORT).show();
//如果是content类型的Uri,则使用普通方式处理
imagePath = getImagePath(uri, null);
} else if("file".equalsIgnoreCase(uri.getScheme())) {
//如果是file类型的uri,则直接获取文件路径
Toast.makeText(this, "success04", Toast.LENGTH_SHORT).show();
imagePath = uri.getPath();
}
displayImage(imagePath);
}
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}
@SuppressLint("Range")
private String getImagePath(Uri uri, String seclection) {
String path = null;
//通过Uri和secletion来获取真实的图片路径
Cursor cursor = getContentResolver().query(uri, null, seclection, null, null);
if(cursor != null) {
if(cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath) {
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}
三 进行实现:
运行结果(手机上的结果):
四:参考:
(40条消息) 《第一行代码》8.3调用摄像头和相册-从相册中选择照片_滚雪球~的博客-CSDN博客
标签:调用,String,相册,data,uri,new,null,优化,out From: https://www.cnblogs.com/wudisanrenzu/p/17410629.html