i am developing a simple text recognition android app (OCR) using TessBaseApi. it consists of 2 buttons . one button is used to upload an image from gallery and set it to an imageview(image that contains some text ) and the second button returns recognized text/string in that image. Everything works fine when i run this app on my real device(samsung galaxy note 4 ). but when i run this app on android studio's emulator image uploads fine from gallery but text does not recognize from it.my app does not throws any exception or error. i am using Android Studio 2.3 with the virtual device "Nexus 5X API 22". this is my code Thanks
package com.textrecognition.nasir.textrecognitiondemo;
import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.googlecode.tesseract.android.TessBaseAPI;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import static android.os.Environment.getExternalStorageDirectory;
public class MainActivity extends AppCompatActivity {
Button upload;
Button txtRecog;
ImageView imgView;
TextView txt;
Uri chosenImageURI;
ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView)findViewById(R.id.myImageView);
txtRecog = (Button) findViewById(R.id.button4);
txt = (TextView) findViewById(R.id.myTextView);
txt.setMovementMethod(new ScrollingMovementMethod());
upload = (Button) findViewById(R.id.button3);
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txt.setText("Text will shown here");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 100);
}
});
txtRecog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txtRecog.setClickable(false);
progress = new ProgressDialog(MainActivity.this) ;
progress.setMessage("Processing");
progress.show();
makeDirectory(); // directories will be made and language files will be copied
}
});
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, 100);
}
}
public void makeDirectory() {
String dirPathSDCard = Environment.getExternalStorageDirectory().toString() + "/TessrectFolder/";
String languageFileDir = "tessData";
//Toast.makeText(MainActivity.this,dirPathSDCard , Toast.LENGTH_SHORT).show();
try {
File dir = new File(dirPathSDCard + languageFileDir);
//Toast.makeText(MainActivity.this, dir.toString(), Toast.LENGTH_SHORT).show();
if (!dir.exists()){
if (!dir.mkdirs())
{
Log.e("Directory Creation Log", "Could not create directories");
}
} else {
Log.e("Directory Creation Log", "Directory already available");
}
} catch (Exception e) {
e.printStackTrace();
}
copyLanguageFileFromAssetsToSDCard(dirPathSDCard, languageFileDir);
recognizeText(chosenImageURI, dirPathSDCard);
}
public void copyLanguageFileFromAssetsToSDCard(String mainPath, String languageFileDir) {
// Toast.makeText(MainActivity.this, "Control reached here", Toast.LENGTH_SHORT).show();
try {
String fileList[] = getAssets().list(languageFileDir);
// Toast.makeText(MainActivity.this, "" + fileList.length, Toast.LENGTH_SHORT);
String str = "";
for(String fileName : fileList) {
String pathToDataFile = mainPath + languageFileDir + "/" + fileName;
if (!(new File(pathToDataFile)).exists()) {
InputStream in = getAssets().open(languageFileDir + "/" + fileName);
OutputStream out = new FileOutputStream(pathToDataFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}}catch (Exception e)
{
e.printStackTrace();
}}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
//Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_SHORT).show();
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);
chosenImageURI = Uri.fromFile(new File(picturePath));
//chosenImageURI = selectedImage;
cursor.close();
Picasso.with(MainActivity.this).load(selectedImage).fit()
.into(imgView);
}
}
public void recognizeText (Uri imgUri, String data_path){
try{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imgUri.getPath(), options);
TessBaseAPI tessApi = new TessBaseAPI();
tessApi.init(data_path, "eng");
tessApi.setImage(bitmap);
String returnedText = "no text found";
returnedText = tessApi.getUTF8Text();
txt.setText(returnedText);
tessApi.end();
txtRecog.setClickable(true);
progress.dismiss();
}catch(Exception e){
e.printStackTrace();
}
}
private void askPermissions(String permissionDetail, int requestCode)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, permissionDetail) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permissionDetail}, requestCode);
} else {
Toast.makeText(MainActivity.this, "Required Permisssions already granted", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case 100:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Required Permisssions granted",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Required Permisssions denied",
Toast.LENGTH_SHORT).show();
}
}
}
}