Wednesday, December 26, 2018

Text Scanner from image on android example

Text image is a type of text in the form of images, so that we can copy this text, we must use the camera to read this type of text and give... thumbnail 1 summary
Text image is a type of text in the form of images, so that we can copy this text, we must use the camera to read this type of text and give it to users in text.

Text Scanner from image on android example

Let's do them as follows
Step 1.
Open android studio –> Select new Project --> Create name projiect--> Select OK
Step 2.
Add library for gradle on file gradle.build you should repeat view Library TextRecognizer on Android here.
Step 3.
Create layout activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Hello World!"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text" />

    <Button
        android:id="@+id/button_camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/camera"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button_gallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/gallery"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>



Step 4.
Create a class have name MainText.class
On this class have these method
Method for Open device default Camera and take snap
private void openCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File imageFile = null;
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            try {
                imageFile = createImageFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (imageFile != null) {
                Uri mImageFileUri;
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
                    mImageFileUri = FileProvider.getUriForFile(this,
                            getResources().getString(R.string.file_provider_authority),
                            imageFile);
                } else {
                    mImageFileUri = Uri.parse("file:" + imageFile.getAbsolutePath());
                }
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageFileUri);
                cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


                startActivityForResult(cameraIntent, REQUEST_FOR_IMAGE_FROM_CAMERA);
            }
        }
    }


Method for Open default device gallery
private void openGallery() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, REQUEST_FOR_IMAGE_FROM_GALLERY);
    }


Create a file for save photo from camera
 private File createImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat")
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "IMG_" + timeStamp;
        File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        try {
            storageDirectory.mkdirs();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return File.createTempFile(imageFileName, ".jpg", storageDirectory);
    }


Have method Override you should use it
@Override
    protected void onActivityResult(final int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        final Uri uri = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            captureImage.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        TextScanner.getInstance(this)
                .init()
                .load(uri)
                .getCallback(new TextExtractCallback() {
                    @Override
                    public void onGetExtractText(List<String> textList) {
                        // Here ypu will get list of text

                        final StringBuilder text = new StringBuilder();
                        for (String s : textList) {
                            text.append(s).append("\n");
                        }
                        recognizeText.post(new Runnable() {
                            @Override
                            public void run() {
                                recognizeText.setText(text.toString());
                            }
                        });

                    }
                });
    }


All code class Main.class
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.skyhope.textrecognizerlibrary.TextScanner;
import com.skyhope.textrecognizerlibrary.callback.TextExtractCallback;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Button buttonGallery, buttonCamera;
    TextView recognizeText;
    ImageView captureImage;

    public static final int REQUEST_FOR_IMAGE_FROM_GALLERY = 101;
    public static final int REQUEST_FOR_IMAGE_FROM_CAMERA = 102;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonGallery = findViewById(R.id.button_gallery);
        buttonCamera = findViewById(R.id.button_camera);
        recognizeText = findViewById(R.id.text);
        captureImage = findViewById(R.id.imageView);


        buttonGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openGallery();
            }
        });

        buttonCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dexter.withActivity(MainActivity.this).withPermission(Manifest.permission.CAMERA).withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        openCamera();
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {

                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {

                    }
                }).check();

            }
        });

    }


    @Override
    protected void onActivityResult(final int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        final Uri uri = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            captureImage.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        TextScanner.getInstance(this)
                .init()
                .load(uri)
                .getCallback(new TextExtractCallback() {
                    @Override
                    public void onGetExtractText(List<String> textList) {
                        // Here ypu will get list of text

                        final StringBuilder text = new StringBuilder();
                        for (String s : textList) {
                            text.append(s).append("\n");
                        }
                        recognizeText.post(new Runnable() {
                            @Override
                            public void run() {
                                recognizeText.setText(text.toString());
                            }
                        });

                    }
                });
    }

    /**
     * Method for Open device default Camera and take snap
     */
    private void openCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File imageFile = null;
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            try {
                imageFile = createImageFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (imageFile != null) {
                Uri mImageFileUri;
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
                    mImageFileUri = FileProvider.getUriForFile(this,
                            getResources().getString(R.string.file_provider_authority),
                            imageFile);
                } else {
                    mImageFileUri = Uri.parse("file:" + imageFile.getAbsolutePath());
                }
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageFileUri);
                cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


                startActivityForResult(cameraIntent, REQUEST_FOR_IMAGE_FROM_CAMERA);
            }
        }
    }

    /**
     * Method for Open default device gallery
     */
    private void openGallery() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, REQUEST_FOR_IMAGE_FROM_GALLERY);
    }

    /**
     * Create a file for save photo from camera
     *
     * @return File
     * @throws IOException Input output error
     */
    private File createImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat")
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "IMG_" + timeStamp;
        File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        try {
            storageDirectory.mkdirs();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return File.createTempFile(imageFileName, ".jpg", storageDirectory);
    }
}


Step 5
And permission on androidmainfest.xml
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />


Step 6.
Run projiect and view result.

No comments

Post a Comment