The image is nt getting converted into text.I am using tessOCR - java

I am building an app on OCR where the image is not getting converted in to the text.
TessOCR.java
public class TessOCR {
public static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/AndroidOCR/";
public static final String lang = "eng";
private static final String TAG = "TESSERACT";
private AssetManager assetManager;
private TessBaseAPI mTess;
Context context;
public TessOCR(AssetManager assetManager) {
Log.i(TAG, DATA_PATH);
this.assetManager = assetManager;
String[] paths = new String[]{"sdcard/tesseract/","sdcard/tesseract/" + "tessdata/"};
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(DATA_PATH + "tessdata/" + "eng.traineddata")).exists()) {
try {
InputStream in = assetManager.open("tessdata/" + "eng.traineddata");
OutputStream out = new FileOutputStream(new File(DATA_PATH + "tessdata/", lang + ".traineddata"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
}
public String getResults(Bitmap bitmap) {
mTess = new TessBaseAPI();
mTess.setDebug(true);
mTess.init("Environment.getExternalStorageDirectory().getPath()", "eng");
mTess.setImage(bitmap);
String result = mTess.getUTF8Text();
Intent intent = new Intent(context,Main2Activity.class);
context.startActivity(intent);
intent.putExtra(result,"key");
return result;
}
public void onDestroy() { mTess.end();
}
}
Main2Activity.java
mTessOCR = new TessOCR(assetManager);
processing1();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.call);
}
private void processing1() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TessOCR(assetManager);
Toast toast = Toast.makeText(Main2Activity.this, "SCANNing", Toast.LENGTH_LONG);
toast.show();
new TessOCR(assetManager).getResults(bitmap);
String value = getIntent().getExtras().getString("key");
TextView tv = (TextView) findViewById(R.id.tvv);
tv.setText(value);
Toast toast1 = Toast.makeText(Main2Activity.this, "SCANNED", Toast.LENGTH_LONG);
toast.show();
new TessOCR(assetManager).onDestroy();
//Intent intent = getIntent();
}
});
}
Logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.veena.cart_for_shopping, PID: 18124
java.lang.IllegalArgumentException: Data path does not exist!
at com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:305)
at com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:282)
at com.example.veena.cart_for_shopping.TessOCR.getResults(TessOCR.java:70)
at com.example.veena.cart_for_shopping.Main2Activity$1.onClick(Main2Activity.java:62)
at android.view.View.performClick(View.java:4796)
at android.view.View$PerformClick.run(View.java:19920)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5383)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:939)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:734)
The app stops when I click on the button and the getResults() method is not able to bitmap image according to the logcat.
What's a solution for this?

Related

Save an Image with TextureView?

I hope you can fix my problem:
I have got a textureview to takes photos but when he capture photos, the file who need to contain the picture is empty. I don't know where and what is the problem. I just think that the problem is when the file is created. Thank you to help me.
This is a part of my code :
private void takePicture() throws CameraAccessException, IOException {
if(cameraDevice == null){
return;
}
CameraManager manager = (CameraManager) Objects.requireNonNull(getContext()).getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
int width = 640;
int height = 480;
if(jpegSizes!=null && jpegSizes.length>0){
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width,height, ImageFormat.JPEG, 1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(reader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE,CameraMetadata.CONTROL_MODE_AUTO);
int rotation = Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));
// First I get the path to gallery and crate new Album to my app
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
mImageFolder = new File(file, "Fluico");
if (!mImageFolder.exists()) {
if (!mImageFolder.mkdirs()) {
Log.d("Fluicophoto", "failed to create directory");
}
}
/*Second I cut mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
from onActivityCreated and add here with the new path from my Album*/
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "IMAGE_" + timestamp + "_";
file = File.createTempFile(prepend, ".jpg", mImageFolder);
Toast.makeText(getContext(), "file need to be save", Toast.LENGTH_SHORT).show();
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
try {
save(bytes);
} finally {
image.close();
}
}
};
reader.setOnImageAvailableListener(readerListener,mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(getContext(), "saved", Toast.LENGTH_SHORT).show();
try{
createCameraPreview();
}catch (CameraAccessException e){
Toast.makeText(getContext(), "capture not comleted", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured( CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
Toast.makeText(getContext(), "capture not configured", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConfigureFailed( CameraCaptureSession session) {
}
},mBackgroundHandler);
}
private void save(byte[] bytes) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.close();
Toast.makeText(getContext(), "it's good", Toast.LENGTH_SHORT).show();
}catch (IOException e){
Toast.makeText(getContext(), "file not found", Toast.LENGTH_SHORT).show();
}
}
Try with below code:
File myDir;
String fname;
String id = "123456";
int count = 0;
String root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/PhotoApp/" + id);
myDir.mkdirs();
count++;
counter.setText(String.valueOf(count));
fname = "" + id + "-" + count + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
This code will create a folder PhotoApp and inside the folder, all the images will store.
You can get full code with the camera in my GitHub:
Link: https://github.com/abhishekhzb/quick_camera

Android Save Video To Gallery

I am developing app using camera on fragment,so for camera I have used this library https://natario1.github.io/CameraView/home because I am using watermarks in camera, now I want to save pictures and videos to gallery, for pictures I have done with below code, for video I done research but not get a solution, for pictures this library is giving bitmap so pictures are saving perfectly but for video I can't figure out kindly help me.
Thank you
public class VideoPreviewActivity extends AppCompatActivity {
private VideoView videoView;
private static VideoResult videoResult;
private Button btnSaveVideo;
public static void setVideoResult(#Nullable VideoResult result) {
videoResult = result;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_preview);
final VideoResult result = videoResult;
if (result == null) {
finish();
return;
}
btnSaveVideo = findViewById(R.id.save_video);
videoView = findViewById(R.id.video);
videoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playVideo();
}
});
AspectRatio ratio = AspectRatio.of(result.getSize());
MediaController controller = new MediaController(this);
controller.setAnchorView(videoView);
controller.setMediaPlayer(videoView);
videoView.setMediaController(controller);
videoView.setVideoURI(Uri.fromFile(result.getFile()));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
ViewGroup.LayoutParams lp = videoView.getLayoutParams();
float videoWidth = mp.getVideoWidth();
float videoHeight = mp.getVideoHeight();
float viewWidth = videoView.getWidth();
lp.height = (int) (viewWidth * (videoHeight / videoWidth));
videoView.setLayoutParams(lp);
playVideo();
if (result.isSnapshot()) {
// Log the real size for debugging reason.
Log.e("VideoPreview", "The video full size is " + videoWidth + "x" + videoHeight);
}
}
});
//Click this button to save video
btnSaveVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Calling 1st Method but not working
//SaveVideo(videoResult.getFile().toString());
//2nd method calling but still not working
saveVideoToInternalStorage(videoResult.getFile().toString());
}
});
}
void playVideo() {
if (!videoView.isPlaying()) {
videoView.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!isChangingConfigurations()) {
setVideoResult(null);
}
}
//first method which I tried but not working
private void SaveVideo(Uri f) {
//I don't know what data type I have to pass in the methods parameters
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath();
File myDir = new File(root + "/Push Videos");
if (!myDir.exists()) {
myDir.mkdirs();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Video-"+ n +".mp4";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
Toast.makeText(VideoPreviewActivity.this, "PUSH Video Saved", Toast.LENGTH_LONG).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//Tried this 2nd method but it is also not giving a desired result
//For saving Video...
private void saveVideoToInternalStorage (String filePath) {
File newfile;
try {
File currentFile = new File(filePath);
String fileName = currentFile.getName();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("videoDir", Context.MODE_PRIVATE);
newfile = new File(directory.getAbsolutePath(), fileName);
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
scanner(filePath);
in.close();
out.close();
Log.v("", "Video file saved successfully.");
Toast.makeText(this, "Push Video Saved TO Gallery", Toast.LENGTH_SHORT).show();
}else{
Log.v("", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
Log.d("Err ", "EXS " + e.getMessage());
e.printStackTrace();
}
}
}

Android copy images to zip

I have a code here it pick image on the gallery and copy the images it pick and zip those. It run smoothly on copying the file. When i include the zip function it gets error on
Compress c = new Compress(path, targetPath+ picturename);.
Here is the code:
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_MULTIPLE = 100;
public static String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
//Setting a directory that is already created on the Storage to copy the file to.
public static String targetPath = ExternalStorageDirectoryPath + "BrokenDave" + File.separator;
String picturename = getPicturename();
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnClickGallery(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case PICK_IMAGE_MULTIPLE:
if (data != null && data.getData() != null) {
Uri uri = data.getData();
path = getPath(uri);
copyFileOrDirectory(path, targetPath + picturename);
Compress c =new Compress(path, targetPath + picturename); //first parameter is d files second parameter is zip file name
c.zip(); //call the zip function
Toast.makeText(this, "File zipped" + path, Toast.LENGTH_SHORT).show();
//get error on calling the zip function
} else {
// Select Multiple
ClipData clipdata = data.getClipData();
if (clipdata != null) {
for (int i = 0; i < clipdata.getItemCount(); i++) {
ClipData.Item item = clipdata.getItemAt(i);
Uri uri = item.getUri();
//ito un path
path = getPath(uri);
//ito un pag copy
copyFileOrDirectory(path, targetPath + picturename);
Compress c =new Compress(path, targetPath + picturename);
c.zip(); //call the zip function
Toast.makeText(this, "Files Deleted" + path, Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
public void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
// 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();
if (destFile != null) {
// pag delete ng file
sourceFile.delete();
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(sourceFile));
sendBroadcast(scanIntent);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
private String getPicturename() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmm");
String timestamp = sdf.format(new Date());
return "Img" + timestamp + ".jpg";
}
}
Here is the compress.java
public class Compress {
private static final int BUFFER = 2048;
public static String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
//Setting a directory that is already created on the Storage to copy the file to.
public static String targetPath = ExternalStorageDirectoryPath + "BrokenDave" + File.separator;
private String[] _files;
// private String targetPath;
public Compress(String[] files, String targetPath) {
_files = files;
}
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(targetPath);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for(int i=0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

AWS Unable to calculate MD5 hash Android

I am uploading image file to S3 via the AWS java SDK, but i am getting the below error while uploading , i have checked my credentials and my bucket they are fine
Unable to calculate MD5 hash: /data/user/0/competent.groove.feetport/files/data/user/0/competent.groove.feetport/app_imageDir/IMG_20161122_073058.jpg: open failed: ENOENT (No such file or directory)
I am capturing the image from camera and saving the image in phone , here is my code
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
//Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT) .show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
// This demo app saves the taken picture to a constant file.
// $ adb pull /sdcard/Android/data/com.google.android.cameraview.demo/files/Pictures/picture.jpg
///storage/7A52-13E8/Android/data/competent.groove.feetport/files/Pictures/picture.jpg
//make a new picture file
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Toast toast = Toast.makeText(getActivity(), "Picture Not saved", Toast.LENGTH_LONG);
toast.show();
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast toast = Toast.makeText(getActivity(), "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
toast.show();
Log.e("-pictureFile--length-----",""+pictureFile.length());
Log.e("---pictureFile-----"+pictureFile.getName(),""+pictureFile.getAbsolutePath());
Log.e("-fileName--",""+fileName);
editor = sharedPref.edit();
editor.putString(Constants.PIC_PATH,""+fileName);
editor.commit();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
});
}
};
String fileName="";
//make picture and save to a folder
private File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
/* File mediaStorageDir = new File("/sdcard/", "JCG Camera");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}*/
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
ContextWrapper cw = new ContextWrapper(getActivity());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
Log.e("---directory-----", "" + directory);
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
///data/user/0/competent.groove.biometric/files/IMG_20160803_181740.jpg
//and make a media file:
fileName = directory + File.separator + "IMG_" + timeStamp + ".jpg";
mediaFile = new File(directory + File.separator + "IMG_" + timeStamp + ".jpg");
Log.e("---extStorageDirectory-----", "" + extStorageDirectory);
//Log.e("---mediaFile-----",""+mediaFile.length());
//Log.e("---mediaFile-----"+mediaFile.getName(),""+mediaFile.getAbsolutePath());
return mediaFile;
}
and my aws code to upload file is
public class UploadAws extends AsyncTask{
private int total, percentage = 0;
Context context;
String s3_server_path = "";
ObscuredSharedPreferences shrdpref;
ObscuredSharedPreferences.Editor editor;
String res = "";
public UploadAws(Context context){
Log.e(""+getClass(), "UploadAws constructor called");
this.context = context;
shrdpref = new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE));
}
#Override
protected Object doInBackground(Object... params) {
try {
Log.d("" + getClass(), "UploadAws doInBackground called");
File pictures = null;
AmazonS3Client s3Client = null;
TransferUtility tx = null;
percentage = 0;
try {
s3_server_path = shrdpref.getString(Constants.PIC_PATH,"");
File dir = context.getFilesDir();
pictures = new File(dir, s3_server_path);
s3Client = new AmazonS3Client(new BasicAWSCredentials(shrdpref.getString(Constants.AWS_Access_Key,""),shrdpref.getString(Constants.AWS_Secret_Key,"")));
tx = new TransferUtility(s3Client,context);
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
Log.e("------File length--------=", "" + pictures.length());
Log.e("------File getName--------=", "" + pictures.getName());
Log.e("------File getAbsolutePath--------=", "" + pictures.getAbsolutePath());
s3Client.setEndpoint("s3.amazonaws.com");
String Feetport_bucket = shrdpref.getString(Constants.fs_bucket, "");
if (s3Client.doesBucketExist(Feetport_bucket)) {
Log.e("Warn", "service called bucket exist");
} else {
s3Client.createBucket(Feetport_bucket);
Log.e("FOS signature", "Bucket created");
}
int imageIndex = pictures.toString().lastIndexOf("/");
String pictureString = pictures.toString().substring(imageIndex + 1, pictures.toString().length());
String selfie_url = "FeetPort/" + shrdpref.getString(Constants.company_name, "") + "/attend/" + Utils.getCurrentDate() + "/" + pictureString;
Log.d("UploadAws selfie_url called: ", "" + selfie_url);
//https://feetport.s3.amazonaws.com/8632/17/20161122/mayank1_I_1624_065610_COL22.jpeg
final TransferObserver observer = tx.upload(Feetport_bucket, pictures.getName(), pictures);
observer.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int arg0, TransferState state) {
Log.e("onStateChanged", "on state changed " + state);
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
Log.e("onProgressChanged", "total bytes " + observer.getBytesTotal());
Log.e("onProgressChanged", "total bytes transfered " + observer.getBytesTransferred());
percentage = (int) (bytesCurrent / bytesTotal * 100);
Log.e("onProgressChanged", "total percentage " + percentage);
}
#Override
public void onError(int arg0, Exception arg1) {
Log.e("onError=" + arg0, "on Error " + arg1.toString());
percentage = 101;
}
});
do {
} while (percentage < 100);
Log.e("percentage", "percentage " + percentage);
if (percentage == 100) {
/**
* CGPL-17 9-5-2016 dynamic bucket and url.
*/
String S3_SERVER = "https://".concat(Feetport_bucket).concat(".s3.amazonaws.com/");
String imageUrl = S3_SERVER + selfie_url;
//Session.setselfie_url(shrdpref, imageUrl);
editor = shrdpref.edit();
editor.putString(Constants.PIC_PATH, "" + imageUrl);
editor.commit();
Log.e("Selfie url ", "imageUrl --- " + imageUrl);
/*JsonParameters object = new JsonParameters(context);
object.markedAttendance(callback);*/
} else {
/*JsonParameters object = new JsonParameters(context);
object.markedAttendance(callback);*/
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
}
This isn't anything related to S3.
ENOENT (No such file or directory) is a local error: file not found.
Take a very close look at the path in the error message. I've included the path here, and added some line breaks for readability. I did not otherwise edit this, and, importantly, I did not paste any of it here more than once:
/data/user/0
/competent.groove.feetport
/files/data/user/0
/competent.groove.feetport
/app_imageDir/IMG_20161122_073058.jpg
I'm not saying that this is wrong, but it certainly looks wrong. It certainly looks like you're trying to upload the file from a path that you have incorrectly constructed, with some duplication in the directory structure... and there's no such directory, no such file.

How to solve the Failure delivering result ResultInfo for camera activity in android

I am creating an android application that will use the OCR library which i got from here
When i am launching an application and after capturing the photo i am getting an error called
Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {reader.test.test.com.visitingcardreader/reader.test.test.com.visitingcardreader.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference
What is that ? and can any one explain me how to solve this.
This my code
public class MainActivity extends Activity {
public static final String PACKAGE_NAME = "com.datumdroid.android.ocr.simple";
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
private static final int CAMERA_REQUEST = 1888;
// You should have the trained data file in assets folder
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
public static final String lang = "eng";
private static final String TAG = "SimpleAndroidOCR.java";
protected Button _button;
// protected ImageView _image;
protected EditText _field;
protected String _path;
protected boolean _taken;
public Intent data;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
// lang.traineddata file with the app (in assets folder)
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
// This area needs work and optimization
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
// _image = (ImageView) findViewById(R.id.image);
_field = (EditText) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = DATA_PATH + "/ocr.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
Log.v(TAG, "Starting Camera app");
startCameraActivity();
}
}
// Simple android photo capture:
// http://labs.makemachine.net/2010/03/simple-android-photo-capture/
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "resultCode: " + resultCode);
if (requestCode ==CAMERA_REQUEST) {
onPhotoTaken(data);
} else {
Log.v(TAG, "User cancelled");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(MainActivity.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG, "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(MainActivity.PHOTO_TAKEN)) {
onPhotoTaken(data);
}
}
protected void onPhotoTaken(Intent data) {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.v(TAG, "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(TAG, "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);
}
// Convert to ARGB_8888, required by tess
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
Log.e(TAG, "Couldn't correct orientation: " + e.toString());
}
// _image.setImageBitmap( bitmap );
Log.v(TAG, "Before baseApi");
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
// You now have the text in recognizedText var, you can do anything with it.
// We will display a stripped out trimmed alpha-numeric version of it (if lang is eng)
// so that garbage doesn't make it to the display.
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if ( lang.equalsIgnoreCase("eng") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
recognizedText = recognizedText.trim();
if ( recognizedText.length() != 0 ) {
_field.setText(_field.getText().toString().length() == 0 ? recognizedText : _field.getText() + " " + recognizedText);
_field.setSelection(_field.getText().toString().length());
}
// Cycle done.
}
}
This is my XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/button_text" />
<EditText
android:id="#+id/field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/text_hint" />
</LinearLayout>
This is my logcat
Process: reader.test.test.com.visitingcardreader, PID: 24739
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {reader.visitingcard.lotus.com.visitingcardreader/reader.visitingcard.lotus.com.visitingcardreader.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3948)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3991)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5769)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference
at reader.visitingcard.lotus.com.visitingcardreader.MainActivity.onPhotoTaken(MainActivity.java:199)
at reader.visitingcard.lotus.com.visitingcardreader.MainActivity.onActivityResult(MainActivity.java:133)
at android.app.Activity.dispatchActivityResult(Activity.java:6845)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3944)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3991) 
at android.app.ActivityThread.-wrap16(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5769) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

Categories

Resources