Get text from image
Output:
Output:
dependencies {
implementation 'com.google.android.gms:play-services-vision:15.0.2'
}
TextExtractUtil
TextExtractUtil
public class TextExtractUtil {
public static String getText(Context context, ImageView imageView) {
TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
StringBuilder imageText = new StringBuilder();
SparseArray<TextBlock> textBlocks = textRecognizer.detect(imageFrame);
for (int i = 0; i < textBlocks.size(); i++) {
TextBlock textBlock = textBlocks.get(textBlocks.keyAt(i));
imageText.append(textBlock.getValue());
}
return String.valueOf(imageText);
}
public static String getText(Context context, Bitmap bitmap) {
TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
StringBuilder imageText = new StringBuilder();
SparseArray<TextBlock> textBlocks = textRecognizer.detect(imageFrame);
for (int i = 0; i < textBlocks.size(); i++) {
TextBlock textBlock = textBlocks.get(textBlocks.keyAt(i));
imageText.append(textBlock.getValue());
}
return String.valueOf(imageText);
}
}
TextExtracterActivity
TextExtracterActivity
public class TextExtracterActivity extends AppCompatActivity {
private ImageView mIVDocument;
private TextView mTVResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_extracter);
mIVDocument = findViewById(R.id.iv_document);
mTVResult = findViewById(R.id.tv_result);
}
public void getText(View view) {
mTVResult.setText(TextExtractUtil.getText(this,
((BitmapDrawable) mIVDocument.getDrawable()).getBitmap()));
}
}
activity_text_extracter.xml
activity_text_extracter.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".TextExtracterActivity">
<ImageView
android:id="@+id/iv_document"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:text="Hello World!"
android:src="@drawable/document"/>
<TextView
android:id="@+id/tv_result"
android:layout_below="@+id/iv_document"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Text"
android:layout_alignParentBottom="true"
android:onClick="getText"/>
</RelativeLayout>