Skip to content

Commit

Permalink
OcrApiService plugin for Android
Browse files Browse the repository at this point in the history
  • Loading branch information
Maxime Schwab authored and Maxime Schwab committed Aug 20, 2012
1 parent a147872 commit 9474d86
Show file tree
Hide file tree
Showing 20 changed files with 1,918 additions and 0 deletions.
81 changes: 81 additions & 0 deletions Android/OcrApiService/com/ocrapiservice/OcrApiServicePlugin.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.ocrapiservice;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;


import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class OcrApiServicePlugin extends Plugin {

public static final String NATIVE_ACTION_STRING="convert";

private String imageUri = "";
private String language = "";
private String apikey = "";
private OcrService apiClient;

public PluginResult execute(String action, JSONArray data, String callbackId) {
if (NATIVE_ACTION_STRING.equals(action)) {
try {
// Retrieve parameters
imageUri = data.getString(0);
language = data.getString(1);
apikey = data.getString(2);

// Load the http client and perform the conversion
apiClient = new OcrService(apikey);

String filePath = getFilePathFromResourcePath(imageUri);
Log.d("filePath : " , filePath);
apiClient.convertToText(language, filePath);
if (!checkRequestSucceed())
throw new Exception(apiClient.getResponseText());

// return the text as success
String recognizedText = apiClient.getResponseText();
return new PluginResult(PluginResult.Status.OK, recognizedText);

}
catch (Exception ex) {
return new PluginResult(PluginResult.Status.ERROR, ex.getMessage());
}


}

return null;
}

// check if the request has succeeded
private boolean checkRequestSucceed(){
if (apiClient.getResponseCode() == 200)
return true;
else
return false;
}

// Convert a resource path to a file path
private String getFilePathFromResourcePath(String resourcePath){
String filePath = "";
// Discussion about the warning
// http://simonmacdonald.blogspot.fr/2012/07/phonegap-android-plugins-sometimes-we.html
ContentResolver cr = this.cordova.getContext().getContentResolver();
String [] projection = {MediaStore.Images.Media.DATA};
Cursor cur = cr.query(Uri.parse(resourcePath), projection, null, null, null);
if(cur != null)
{
cur.moveToFirst();
filePath = cur.getString(0);
}

return filePath;
}


}
118 changes: 118 additions & 0 deletions Android/OcrApiService/com/ocrapiservice/OcrService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package com.ocrapiservice;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class OcrService {
public final String SERVICE_URL = "http://api.ocrapiservice.com/1.0/rest/ocr";

private final String PARAM_IMAGE = "image";
private final String PARAM_LANGUAGE = "language";
private final String PARAM_APIKEY = "apikey";

private String apiKey;

private int responseCode;
private String responseText;

public OcrService(final String apiKey) {
this.apiKey = apiKey;
}

/*
* Convert image to text.
*
* @param language The image text language.
* @param filePath The image absolute file path.
*
* @return true if everything went okay and false if there is an error with sending and receiving data.
*/
public boolean convertToText(final String language, final String filePath) {
try {
sendImage(language, filePath);

return true;
} catch (ClientProtocolException e) {
e.printStackTrace();

return false;
} catch (IOException e) {
e.printStackTrace();

return false;
}
}

/*
* Send image to OCR service and read response.
*
* @param language The image text language.
* @param filePath The image absolute file path.
*
*/
private void sendImage(final String language, final String filePath) throws ClientProtocolException, IOException {
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(SERVICE_URL);

final FileBody image = new FileBody(new File(filePath));

final MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(PARAM_IMAGE, image);
reqEntity.addPart(PARAM_LANGUAGE, new StringBody(language));
reqEntity.addPart(PARAM_APIKEY, new StringBody(getApiKey()));
httppost.setEntity(reqEntity);

final HttpResponse response = httpclient.execute(httppost);
final HttpEntity resEntity = response.getEntity();
final StringBuilder sb = new StringBuilder();
if (resEntity != null) {
final InputStream stream = resEntity.getContent();
byte bytes[] = new byte[4096];
int numBytes;
while ((numBytes=stream.read(bytes))!=-1) {
if (numBytes!=0) {
sb.append(new String(bytes, 0, numBytes));
}
}
}

setResponseCode(response.getStatusLine().getStatusCode());

setResponseText(sb.toString());
}

public int getResponseCode() {
return responseCode;
}

public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}

public String getResponseText() {
return responseText;
}

public void setResponseText(String responseText) {
this.responseText = responseText;
}

public String getApiKey() {
return apiKey;
}

public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
}
16 changes: 16 additions & 0 deletions Android/OcrApiService/ocrapiservice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright (C) 2012 by Guillaume Charhon
*/
var ocrapiservice = {

// parameters
// - imageURI : URI of the image to convert
// - language : 2 letter language code (ex : "en" for english)
// - apikey : Your api key displayed in your http://ocrapiservice.com dashboard

convert: function (success, fail, imageURI,language, apikey ) {
return cordova.exec( success, fail,
"OcrApiServicePlugin",
"convert", [imageURI, language, apikey]);
}
};
109 changes: 109 additions & 0 deletions Android/OcrApiService/org/apache/http/entity/mime/FormBodyPart.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/

package org.apache.http.entity.mime;

import org.apache.http.entity.mime.content.ContentBody;

/**
* FormBodyPart class represents a content body that can be used as a part of multipart encoded
* entities. This class automatically populates the header with standard fields based on
* the content description of the enclosed body.
*
* @since 4.0
*/
public class FormBodyPart {

private final String name;
private final Header header;

private final ContentBody body;

public FormBodyPart(final String name, final ContentBody body) {
super();
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
if (body == null) {
throw new IllegalArgumentException("Body may not be null");
}
this.name = name;
this.body = body;
this.header = new Header();

generateContentDisp(body);
generateContentType(body);
generateTransferEncoding(body);
}

public String getName() {
return this.name;
}

public ContentBody getBody() {
return this.body;
}

public Header getHeader() {
return this.header;
}

public void addField(final String name, final String value) {
if (name == null) {
throw new IllegalArgumentException("Field name may not be null");
}
this.header.addField(new MinimalField(name, value));
}

protected void generateContentDisp(final ContentBody body) {
StringBuilder buffer = new StringBuilder();
buffer.append("form-data; name=\"");
buffer.append(getName());
buffer.append("\"");
if (body.getFilename() != null) {
buffer.append("; filename=\"");
buffer.append(body.getFilename());
buffer.append("\"");
}
addField(MIME.CONTENT_DISPOSITION, buffer.toString());
}

protected void generateContentType(final ContentBody body) {
StringBuilder buffer = new StringBuilder();
buffer.append(body.getMimeType()); // MimeType cannot be null
if (body.getCharset() != null) { // charset may legitimately be null
buffer.append("; charset=");
buffer.append(body.getCharset());
}
addField(MIME.CONTENT_TYPE, buffer.toString());
}

protected void generateTransferEncoding(final ContentBody body) {
addField(MIME.CONTENT_TRANSFER_ENC, body.getTransferEncoding()); // TE cannot be null
}

}
Loading

0 comments on commit 9474d86

Please sign in to comment.