android安卓文字识别 调用百度api 后端:Spring Boot

安卓文字识别 + Spring Boot后端

一、项目概述

  • 项目效果展示

安卓期末作业-文字识别

  • android app 端:

    • 登录注册页面、

      • 通过注册页面注册账号,会保存在后端的MySQL数据库
      • 登录页面会查询数据库核对信息进行登录操作
    • 文字识别页面

      • 通过调用相册选取图片,将图片使用百度开放平台文字识别获得识别后的文字
      • 识别后的文字会储存在数据库中,识别记录会保存
    • 网络请求

      • OKHttp发送POST请求存储数据
      • OKHttp发送GET请求获取数据
  • 后端

    • Spring Boot

      • 通过Controller映射请求的URL,实现前后端分离
    • JPA

      • 通过实体类映射数据库字段名,绑定数据库连接
      • 继承Repository接口实现基本的数据库操作语句
    • MySQL

      • user表存储用户登录信息,infor_record表存储识别记录
      • 两表通过username字段,进行数据耦合
  • 项目结构简图

在这里插入图片描述

二、安卓app

登录页面

类代码

public class LoginActivity extends Activity {


    private Button btnLogin = null;
    private Button btnRegister = null;
    private EditText username = null;
    private EditText password = null;

    private ProgressDialog progressDialog;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideProgressDialog();
            String usernameStr = username.getText().toString();
            //将用户名称传入到下个页面,并且跳转
            Bundle bundle = new Bundle();
            bundle.putString("username", usernameStr);
            Intent intent = new Intent(getApplicationContext(), WordFindActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);
        username  = findViewById(R.id.login_username);
        password = findViewById(R.id.login_password);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usernameStr = username.getText().toString();
                String passwordStr = password.getText().toString();
                if (usernameStr.length() == 0) {
                    Toast.makeText(getApplicationContext(), "请输入用户名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (passwordStr.length() == 0) {
                    Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                showProgressDialog("登陆中", "请稍后");
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
                        Request request = new Request.Builder().url(UrlAddress.getUrl() + "getUserByName/" + usernameStr)
                                .get().build();
                        Call call = client.newCall(request);
                        try {
                            Response response = call.execute();
                            String result = new String(response.body().bytes());
                            System.out.println("===========>登录查询结果" + result);
                            //如果返回值为空,用户不存在
                            if (result.length() != 0) {
                                User user = JsonUtils.jsonToPojo(result, User.class);
                                //如果密码正确
                                if (user.getPassword().equals(passwordStr)) {
                                    handler.sendEmptyMessage(1);
                                    return;
                                } else {
                                    //如果密码不正确
                                    Looper.prepare();
                                    hideProgressDialog();
                                    Toast.makeText(getApplicationContext(), "密码不正确", Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }
                            } else {
                                //如果用户名不存在
                                Looper.prepare();
                                hideProgressDialog();
                                Toast.makeText(getApplicationContext(), "用户名不存在", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(intent);
            }
        });


    }
    /*
     * 提示加载
     */
    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(LoginActivity.this, title,
                    message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }
    /*
     * 隐藏提示加载
     */
    public void hideProgressDialog() {

        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity">

    <!--app:srcCompat="@drawable/_11"-->

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="216dp"
        android:layout_height="141dp"
        android:src="@drawable/icon"
        app:layout_constraintBottom_toTopOf="@+id/login_username"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.512"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.608" />

    <EditText
        android:id="@+id/login_username"
        style="@style/Widget.AppCompat.AutoCompleteTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="52dp"
        android:ems="10"
        android:hint="请输入账号"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/login_password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/login_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="64dp"
        android:ems="10"
        android:hint="请输入密码"
        android:inputType="textPassword"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/btn_login"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="SpeakableTextPresentCheck" />

    <Button
        android:id="@+id/btn_login"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="164dp"
        android:background="@drawable/shape_bt"
        android:text="登录"
        android:textColor="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.269"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btn_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="164dp"
        android:background="@drawable/shape_bt"
        android:text="注册"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.687"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

注册页面

类代码

public class RegisterActivity extends Activity {
    private ProgressDialog progressDialog;

    private Button btnBack = null;
    private Button btnRegisterEnd = null;
    private EditText username = null;
    private EditText password = null;
    private EditText phoneNum = null;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideProgressDialog();
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnBack = findViewById(R.id.back);
        btnRegisterEnd = findViewById(R.id.btn_register_end);
        username = findViewById(R.id.register_username);
        password = findViewById(R.id.register_password);
        phoneNum = findViewById(R.id.register_phone_num);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
            }
        });

        btnRegisterEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usernameStr = username.getText().toString();
                String passwordStr = password.getText().toString();
                String phoneNumStr = phoneNum.getText().toString();
                if (usernameStr.length() == 0) {
                    Toast.makeText(getApplicationContext(), "用户名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (passwordStr.length() == 0) {
                    Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (phoneNumStr.length() == 0) {
                    Toast.makeText(getApplicationContext(), "手机号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                showProgressDialog("请稍后", "提交中");
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
                        Request request = new Request.Builder().url(UrlAddress.getUrl() + "getUserByName/" + usernameStr)
                                .get().build();
                        Call call = client.newCall(request);
                        try {
                            Response response = call.execute();
                            String result = new String(response.body().bytes());
                            System.out.println("============>" + result);
                            System.out.println("======" + result.length());
                            System.out.println("======" + result == null);
                            //判断是否已经注册
                            if (result.length() != 0) {

                                Looper.prepare();
                                Toast.makeText(getApplicationContext(), "用户名已经注册!", Toast.LENGTH_SHORT).show();
                                hideProgressDialog();
                                Looper.loop();
                                return;
                            }
                            //网络请求发送到数据库
                            //将结果存储到数据库
                            OkHttpClient okHttpClient = new OkHttpClient();
                            RequestBody requestBody = new FormBody.Builder()
                                    .build();
                            System.out.println("======================>" + "注册post: http://192.168.1.107/addUser/" + usernameStr + "/" + passwordStr + "/"  + phoneNumStr);
                            Request request2 = new Request.Builder()
                                    .url(UrlAddress.getUrl() + "addUser/" + usernameStr + "/" + passwordStr + "/"  + phoneNumStr)
                                    .post(requestBody)
                                    .build();

                            okHttpClient.newCall(request2).enqueue(new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    System.out.println("===================>" + "注册post失败");
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    System.out.println("===================>" + "注册post成功");
                                    System.out.println(response.protocol() + " " + response.code() + " " + response.message());
                                    Headers headers = response.headers();
                                    for (int i = 0; i < headers.size(); i++) {
                                        System.out.println(headers.name(i) + ":" + headers.value(i));;
                                    }
                                    System.out.println("onResponse: " + response.body().string());
                                    handler.sendEmptyMessage(1);
                                }
                            });

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

            }
        });

    }

    /*
     * 提示加载
     */
    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(RegisterActivity.this, title,
                    message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }

    /*
     * 隐藏提示加载
     */
    public void hideProgressDialog() {

        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }
}

布局页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed"
    android:orientation="vertical">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#ffffff">

        <Button
            android:id="@+id/back"
            style="@style/Widget.AppCompat.Button.Small"
            android:layout_width="76dp"
            android:layout_height="wrap_content"
            android:text="返回" />
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="24dp"
        android:layout_marginBottom="5dp"
        android:text="请输入用户名"
        android:textColor="#808080" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#ffffff"
        android:orientation="horizontal">

        <TextView
            android:layout_width="64dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:text="用户名"
            android:textColor="#000000" />


        <EditText
            android:id="@+id/register_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="48dp"
            android:background="@drawable/number_shape"
            android:hint="输入您的用户名"
            android:paddingLeft="16dp"
            android:textSize="16sp"
            tools:ignore="TouchTargetSizeCheck" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#ffffff"
        android:orientation="horizontal">

        <TextView
            android:layout_width="64dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:text="密码"
            android:textColor="#000000" />


        <EditText
            android:id="@+id/register_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="48dp"
            android:background="@drawable/number_shape"
            android:hint="输入您的密码"
            android:paddingLeft="16dp"
            android:textSize="16sp"
            tools:ignore="TouchTargetSizeCheck" />
    </LinearLayout>


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="24dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"
        android:text="绑定您的手机"
        android:textColor="#808080" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#ffffff"
        android:orientation="horizontal">

        <TextView
            android:layout_width="64dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:text="手机号"
            android:textColor="#000000" />


        <EditText
            android:id="@+id/register_phone_num"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="48dp"
            android:background="@drawable/number_shape"
            android:hint="请输入您的手机号"
            android:paddingLeft="16dp"
            android:textSize="16sp"
            tools:ignore="TouchTargetSizeCheck" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_register_end"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="48dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/shape_bt"
        android:text="注册"
        android:textSize="16sp" />
</LinearLayout>

文字识别页面

类代码

public class WordFindActivity extends Activity {
    private static int RESULT_LOAD_IMAGE = 10;
    private static final int PERMISSION_REQUEST = 1001;
    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA,Manifest.permission.CALL_PHONE,Manifest.permission.READ_EXTERNAL_STORAGE};
    private ProgressDialog progressDialog;
    List<String> permissionsList = new ArrayList<>();
    static Bitmap resBitMap;
    EditText showImgText = null;
    static User user = new User();
    static List<String> textCoures = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_find);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        //为按钮设置点击事件
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //点击事件,而重定向到图片库
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()方法。
                startActivityForResult(intent, RESULT_LOAD_IMAGE);
            }
        });
        Button buttonShowText = (Button) findViewById(R.id.showText);
        buttonShowText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        getApplicationContext(), ImgTextListActivity.class);
                //如果识别记录不为空或者长度为0,就加入到记录中
                if (showImgText != null) {
                    String str = showImgText.getText().toString();
                    if (str.length() > 0) {
                        //网络请求发送到数据库
                        //将识别结果存入数据库
                        OkHttpClient okHttpClient = new OkHttpClient();
                        RequestBody requestBody = new FormBody.Builder()
                                .build();
                        System.out.println("======================>" + "http://192.168.1.107/addInfoRecord/" + user.getName() + "/" + str);
                        Request request = new Request.Builder()
                                .url(UrlAddress.getUrl() + "addInfoRecord/" + user.getName() + "/" + str)
                                .post(requestBody)
                                .build();

                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                System.out.println("===================>" + "post失败");
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                System.out.println("===================>" + "post成功");
                                System.out.println(response.protocol() + " " + response.code() + " " + response.message());
                                Headers headers = response.headers();
                                for (int i = 0; i < headers.size(); i++) {
                                    System.out.println(headers.name(i) + ":" + headers.value(i));;
                                }
                                System.out.println("onResponse: " + response.body().string());
                            }
                        });
                    }
                    //添加数据
                    //intent.putStringArrayListExtra("records", (ArrayList<String>) textCoures);
                }
                Bundle bundle = new Bundle();
                bundle.putString("username", user.getName());
                intent.putExtras(bundle);
                //跳转到记录list
                startActivity(intent);


            }
        });

        initPermissions();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 将用户信息更新
        Bundle extras= getIntent().getExtras();
        if (extras != null && extras.getString("username") != null) {
            user.setName(extras.getString("username"));
        }
        //user.setName("张三");
    }

    /**
     * 请求权限
     */
    private void initPermissions() {
        permissionsList.clear();

        //判断哪些权限未授予
        for(String permission : permissions){
            if(ActivityCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED){
                permissionsList.add(permission);
            }
        }

        //请求权限
        if(!permissionsList.isEmpty()){
            String[] permissions = permissionsList.toArray(new String[permissionsList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(WordFindActivity.this, permissions, PERMISSION_REQUEST);
        }
    }
    //用户选择一张图片,onActivityResult()方法将会被调用,
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        showImgText = null;
        //我们需要判断requestCode是否是我们之前传给startActivityForResult()方法的RESULT_LOAD_IMAGE,并且返回的数据不能为空
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            //查询我们需要的数据
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            showImgText = (EditText) findViewById(R.id.showImgText);
            resBitMap = BitmapFactory.decodeFile(picturePath);
            imageView.setImageBitmap(resBitMap);
            System.out.println("=======================================================");
        }


        //等待识别消息框
        showProgressDialog("识别中", "请等待");

        EditText wordText = showImgText;
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = generalBasic();
                RecognitionResultBean bean = JsonUtils.jsonToPojo(json, RecognitionResultBean.class);
                String str = "";
                for (RecognitionResultBean.WordsResultBean resultBean : bean.getWords_result()) {
                    str += resultBean.getWords();
                };
                System.out.println(str);

                Looper.prepare();
                if (wordText != null) {
                    wordText.setText(str);
                    //隐藏等待框
                    hideProgressDialog();
                }
                Looper.loop();
            }
        }).start();
    }

    public String generalBasic() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        try {
            // 本地文件路径
            //System.out.println("------" + System.getProperty("user.dir"));
            //String filePath = "app/1.png";



            String base64Img = getImgBase64(resBitMap);
            String imgParam = URLEncoder.encode(base64Img, "UTF-8");

            String param = "image=" + imgParam;
            /*System.out.println("=================>>>>>" + param);*/
            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = AuthService.getAuth();

            String result = HttpUtil.post(url, accessToken, param);
            //System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public String getImgBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imgData = baos.toByteArray();
        String imgStr = Base64Util.encode(imgData);
        return imgStr;
    }


    /*
     * 提示加载
     */
    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(WordFindActivity.this, title,
                    message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }

    /*
     * 隐藏提示加载
     */
    public void hideProgressDialog() {

        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

}

布局页面

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

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_weight="1" />

    <EditText
        android:id="@+id/showImgText"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:editable="false"
        tools:ignore="SpeakableTextPresentCheck" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="130dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/buttonLoadPicture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="85dp"
            android:layout_weight="0"
            android:text="选择图片"
            android:background="@drawable/shape_bt"/>
        <Button
            android:id="@+id/showText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="40dp"
            android:layout_weight="0"
            android:background="@drawable/shape_bt"
            android:text="查看记录" />


    </LinearLayout>


</LinearLayout>

识别记录列表页面

类代码

public class ImgTextListActivity extends Activity {
    static ListView textInfo;
    static List<String> textCoures = new ArrayList<>();
    static User user = new User();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, textCoures);
            textInfo.setAdapter(adapter);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img_text_list);
        textInfo = (ListView) findViewById(R.id.textInfoList);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //获取user的数据集合
        // 将用户信息更新
        Bundle extras= getIntent().getExtras();
        if (extras != null) {
            String username = extras.getString("username");
            if (username != null) {
                user.setName(username);
            }
        }

        boolean flag = true;

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
                Request request = new Request.Builder().url(UrlAddress.getUrl() + "getInfoRecordsByName/" + user.getName())
                        .get().build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    System.out.println("============>" + "请求成功");
                    String responseStr = new String(response.body().bytes());
                    System.out.println(responseStr);
                    List<InfoRecord> infoRecord = JsonUtils.jsonToList(responseStr, InfoRecord.class);
                    //将record转为字符串
                    RecordList recordList = new RecordList(infoRecord);
                    textCoures = recordList.getString();
                    handler.sendEmptyMessage(1);

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

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".ImgTextListActivity">

    <ListView
        android:id="@+id/textInfoList"
        android:layout_width="409dp"
        android:layout_height="729dp"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp" />
</LinearLayout>

百度开发平台 文字识别 api

在百度开放平台中选中图像识别,找到文字识别,然后创建应用,这是一个收费项目,但每天都有免费的次数。

要使用这个功能必须先要鉴权,需要用到一些Java的工具类,请在官方下载,详情官方文档

百度开放平台:http://ai.baidu.com

三、后端

SpringBoot

controller代码

@RestController
public class InfoRecordController {
    @Autowired
    InfoRecordRepository infoRecordRepository;

    @GetMapping("/getInfoRecordsByName/{username}")
    public List<InfoRecord> getInfoRecordsByUsername(@PathVariable("username") String username) {
        return infoRecordRepository.getInfoRecordsByUsername(username);
    }
    @PostMapping("/addInfoRecord/{username}/{record}")
    public Msg addInfoRecord(@PathVariable("username") String name,
                             @PathVariable("record") String record) {
        infoRecordRepository.save(new InfoRecord(name, record));
        return Msg.setCode("success");
    }
}
@RestController
public class UserController {
    @Autowired
    UserRepository userRepository;
    @Autowired
    InfoRecordRepository infoRecordRepository;

    /*@GetMapping("/getUser/{username}")
    public Optional<User> getUserPwd(@PathVariable("username") Integer username) {
       return userRepository.findById(username);
    }*/
    //根据名字查询
    @GetMapping("/getUserByName/{username}")
    public User getUserByName(@PathVariable("username") String username) {
        return userRepository.findByName(username);
    }
    @PostMapping("/addUser/{name}/{password}/{phoneNum}")
    public Msg addUser(@PathVariable("name") String name,
                       @PathVariable("password") String password,
                       @PathVariable("phoneNum") String phoneNum) {
        if (userRepository.findByName(name) != null) {
            return Msg.setCode("failed");
        }
        userRepository.save(new User(name, password, phoneNum));
        return Msg.setCode("success");
    }

}
JPA

实体类映射

@Entity
@Data
public class InfoRecord {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY) // 设置mysql id自增
    private Integer id;
    private String username;
    private String record;

    public InfoRecord() {

    }
    public InfoRecord(String username, String record) {
        this.username = username;
        this.record = record;
    }
}
@Entity
@Data
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 设置mysql id自增
    private Integer id;
    private String name;
    private String password;
    private String phoneNum;

    public User() {

    }
    public User (String name, String password, String phoneNum) {
        this.name = name;
        this.password = password;
        this.phoneNum = phoneNum;
    }
}

用于标识请求成功或者失败的工具类

@Data
public class Msg {
    private String code;
    private Msg(String code) {
        this.code = code;
    }
    public static Msg setCode(String code) {
        return new Msg(code);
    }

    @Override
    public String toString() {
        return "Msg{" +
                "code='" + code + '\'' +
                '}';
    }
}

Repository接口继承

public interface UserRepository extends JpaRepository<User, Integer> {
    User findByName(String name);
}
public interface InfoRecordRepository extends JpaRepository<InfoRecord, Integer> {
    List<InfoRecord> getInfoRecordsByUsername(String username);
}
MySQL

User表

在这里插入图片描述

​ name属性设置为唯一,用户不能重名

Info_record表
在这里插入图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值