Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

i cant crop the selected image.... after selecting the image the app retrun home page #830

Open
jestag4 opened this issue Apr 10, 2021 · 1 comment

Comments

@jestag4
Copy link

jestag4 commented Apr 10, 2021

package com.example.image2text;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

public class MainActivity extends AppCompatActivity {

EditText mResultEt;
ImageView mPreview;

private static final int CAMERA_REQUEST_CODE = 200;
private static final int STORAGE_REQUEST_CODE = 400;
private static final int IMAGE_PICK_GALLERY_CODE = 1000;
private static final int IMAGE_PICK_CAMERA_CODE = 1001;

String[] cameraPermission;
String[] storagePermission;

Uri image_Uri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setSubtitle("Click + button to scan Image");

    mResultEt = findViewById(R.id.resultEt);
    mPreview = findViewById(R.id.imageIv);

    //camera permission
    cameraPermission = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
    storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
}

//action bar
@OverRide
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.addImage){
        showImageImportDialog();
    }
    if (id == R.id.settings){
        Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
    }
    return super.onOptionsItemSelected(item);
}

private void showImageImportDialog() {
    //display
    String[] items = {"Camera", "Gallery"};
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    //title
    dialog.setTitle("Select Image");
    dialog.setItems(items, (dialog1, which) -> {
        if (which == 0){
            //camera option
            if (!checkCameraPermission()){
                requestCameraPermissions();
            }
            else {
                //permission allowed
                pickCamera();
            }
        }
        if (which == 1){
            //gallery option
            if (!checkStoragePermission()){
                requestStoragePermissions();
            }
            else {
                //permission allowed
                pickGallery();
            }
        }

    });
    dialog.create().show(); //show dialog
}

private void pickGallery() {
    //pick image from gallery
    Intent intent = new Intent(Intent.ACTION_PICK);
    //set intent type
    intent.setType("image/*");
    startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);

}

private void pickCamera() {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, "NewPic");
    values.put(MediaStore.Images.Media.DESCRIPTION, "Image To Text");
    image_Uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_Uri);
    startActivityForResult(cameraIntent,IMAGE_PICK_CAMERA_CODE);

}

private void requestStoragePermissions() {
    ActivityCompat.requestPermissions(this,storagePermission, STORAGE_REQUEST_CODE );

}

private boolean checkStoragePermission(){
    boolean result = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
    return result;
}

private void requestCameraPermissions() {
    ActivityCompat.requestPermissions(this,cameraPermission, CAMERA_REQUEST_CODE );
}

private boolean checkCameraPermission() {
    boolean result = ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
    boolean result1 = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
    return result && result1;
}

//handle permission result
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case CAMERA_REQUEST_CODE:
            if (grantResults.length>0){
                boolean cameraAccepted = grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED;
                boolean writeStorageAccepted = grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED;
                if (cameraAccepted && writeStorageAccepted){
                    pickCamera();
                }
                else {
                    Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();
                }
            }
            break;

        case STORAGE_REQUEST_CODE:
            if (grantResults.length>0){
                boolean writeStorageAccepted = grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED;
                if (writeStorageAccepted){
                    pickGallery();
                }
                else {
                    Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();
                }
            }
            break;
    }
}

//handle image result
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_OK) {
        if (requestCode == IMAGE_PICK_GALLERY_CODE) {
            //got image from gallery
            Uri image_Uri = data.getData();
            CropImage.activity(image_Uri)
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1, 1)
                    .start(this);
         }
        if (requestCode == IMAGE_PICK_CAMERA_CODE) {
            //got image from camera
            CropImage.activity(image_Uri)
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1, 1)
                    .start(this);
        }
    }
    //get cropped image
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();
            mPreview.setImageURI(resultUri);

            //get drawable bitmap
            BitmapDrawable bitmapDrawable = (BitmapDrawable) mPreview.getDrawable();
            Bitmap bitmap = bitmapDrawable.getBitmap();
            TextRecognizer recognizer = new TextRecognizer.Builder(getApplicationContext()).build();

            if (!recognizer.isOperational()) {
                Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
            } else {
                Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                SparseArray<TextBlock> items = recognizer.detect(frame);
                StringBuilder sb = new StringBuilder();
                //get text from sb
                for (int i = 0; i < items.size(); i++) {
                    TextBlock myItem = items.valueAt(i);
                    sb.append(myItem.getValue());
                    sb.append("\n");
                }
                //set text to edit text
                mResultEt.setText(sb.toString());
            }
        } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            //if there is any error show it
            Exception error = result.getError();
            Toast.makeText(this, "" + error, Toast.LENGTH_SHORT).show();
        }
    }
}

}

@Canato
Copy link

Canato commented Apr 12, 2021

@jestag4
🚨🚨🚨🚨🚨 THIS LIBRARY IS NOT MAINTAINED, PLEASE READ THIS 🚨🚨🚨🚨🚨 #818

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants