com.dastardlylabs.ti.ocrdroid.OcrdroidModule.java Source code

Java tutorial

Introduction

Here is the source code for com.dastardlylabs.ti.ocrdroid.OcrdroidModule.java

Source

/**
 * This file was auto-generated by the Titanium Module SDK helper for Android
 * Appcelerator Titanium Mobile
 * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 *
 */
package com.dastardlylabs.ti.ocrdroid;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;

import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.common.Log;
import org.json.JSONArray;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;

import com.dastardlylabs.android.util.StorageHelper;
import com.googlecode.tesseract.android.TessBaseAPI;

@Kroll.module(name = "Ocrdroid", id = "com.dastardlylabs.ti.ocrdroid")
public class OcrdroidModule extends KrollModule {

    // Standard Debugging variables
    private static final String LCAT = "TesseractModule";
    private static Context appContext;
    private static StorageHelper storageHelper;
    //private static final boolean DBG = TiConfig.LOGD;
    //private static boolean supportsExternalStorage;   

    // You can define constants with @Kroll.constant, for example:
    // @Kroll.constant public static final String EXTERNAL_NAME = value;

    public OcrdroidModule() {
        super();
    }

    @Kroll.onAppCreate
    public static void onAppCreate(TiApplication app) {
        appContext = app.getApplicationContext();
        storageHelper = new StorageHelper(appContext);

        Log.d(LCAT, "inside onAppCreate");
        if (!tessDataExists()) {
            unpackTessData();
        }
    }

    private static File getTessDataDirectory() {
        return storageHelper.getStorageDirectory();
    }

    private static void unpackTessData() {

        String assetName = "tess.zip", assetPath, outputDir = getTessDataDirectory().getAbsolutePath();
        File assetTmpFile;

        Log.i(LCAT, "Extracting " + assetName);
        assetTmpFile = storageHelper.copyAssetToTmp(assetName);
        assetPath = assetTmpFile.getAbsolutePath();

        try {
            Log.d(LCAT, "assetFile Path: " + assetPath);
            com.dastardlylabs.android.util.ZipHelper.extract(assetPath, outputDir);
        } catch (IOException e) {
            Log.e(LCAT, "Asset unpacking failed: " + e.getLocalizedMessage());
        } finally {
            if (assetTmpFile != null && assetTmpFile.exists())
                assetTmpFile.delete();
        }

    }

    private static boolean tessDataExists() {
        ArrayList<String> dataFiles = new ArrayList<String>();
        Collections.addAll(dataFiles, getTessDataDirectory().list());

        JSONArray fred = new JSONArray(dataFiles);

        Log.d(LCAT, "DataFiles list: " + fred.toString());

        return dataFiles.contains((Object) "tessdata");
    }

    @Kroll.method
    @SuppressWarnings("rawtypes")
    public String ocr(HashMap _config) {
        assert (_config != null);
        String dataParentPath = getTessDataDirectory().getAbsolutePath(), //= (String) _config.get("dataParent"),
                imagePath = StorageHelper.stripFileUri((String) _config.get("image")),
                language = (String) _config.get("lang");

        try {
            if (!tessDataExists())
                unpackTessData();
        } catch (Exception e) {
            // catch failure and bubble up failure message and options
            // else continue.
        }

        Log.d(LCAT, "ocr called");
        Log.d(LCAT, "Setting parent directory for tessdata as DATAPATH".replace("DATAPATH",
                dataParentPath /*DATA_PATH*/));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
        //bitmap.getConfig()

        try {
            ExifInterface exif = new ExifInterface(imagePath);
            int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);

            Log.v(LCAT, "Orient: " + exifOrientation);

            int rotate = 0;
            switch (exifOrientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            }

            Log.v(LCAT, "Rotation: " + rotate);

            if (rotate != 0) {

                // Getting width & height of the given image.
                int w = bitmap.getWidth();
                int h = bitmap.getHeight();

                // Setting pre rotate
                Matrix mtx = new Matrix();
                mtx.preRotate(rotate);

                // Rotating Bitmap
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
                // tesseract req. ARGB_8888
                bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
            }

        } catch (IOException e) {
            Log.e(LCAT, "Rotate or coversion failed: " + e.toString());
        }

        //        ImageView iv = (ImageView) findViewById(R.id.image);
        //        iv.setImageBitmap(bitmap);
        //        iv.setVisibility(View.VISIBLE);

        Log.v(LCAT, "Before baseApi");

        TessBaseAPI baseApi = new TessBaseAPI();
        baseApi.setDebug(true);
        baseApi.init(dataParentPath /*DATA_PATH*/, language);
        baseApi.setImage(bitmap);
        //baseApi.get
        String recognizedText = baseApi.getUTF8Text();
        baseApi.end();

        Log.v(LCAT, "OCR Result: " + recognizedText);

        // clean up and show
        if (language.equalsIgnoreCase("eng")) {
            recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
        }

        return recognizedText.trim();
    }

}