Why is Parcel File Descriptor throwing FileNotFounException even if the imageUri is not null or empty. I have selected a file from my gallery using Intent. I also toast the value of "imageUri", it prints.
ParcelFileDescriptor percelFileDescriptor;
Toast.makeText(getApplicationContext(),""+imageUri.toString(),Toast.LENGTH_LONG).show();
try {
percelFileDescriptor = getContentResolver().openFileDescriptor(imageUri, "r");
image = BitmapFactory.decodeFileDescriptor(percelFileDescriptor.getFileDescriptor());
modified_img_bitmap = image;
percelFileDescriptor.close();
picked_image.setImageBitmap(image);
} catch (FileNotFoundException e) {
System.out.println("File Not Found: " + e.toString());
Toast.makeText(getApplicationContext(),"File not found: "+e.toString(),Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"IO Error: "+e.toString(),Toast.LENGTH_LONG).show();
System.out.println("IO Exception: " + e.toString());
}
}
I tried your code and that works. Please, post your full code.
That works:
private final int GALLERY_REQUEST = 0;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent pictureActionIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pictureActionIntent, GALLERY_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
switch (requestCode)
{
case GALLERY_REQUEST:
if (data != null)
{
imageUri = data.getData();
Bitmap image = null;
Bitmap modified_img_bitmap = null;
ImageView picked_image = (ImageView)findViewById(R.id.imageView);
ParcelFileDescriptor percelFileDescriptor;
Toast.makeText(getApplicationContext(),""+imageUri.toString(),Toast.LENGTH_LONG).show();
try
{
percelFileDescriptor = getContentResolver().openFileDescriptor(imageUri, "r");
image = BitmapFactory.decodeFileDescriptor(percelFileDescriptor.getFileDescriptor());
modified_img_bitmap = image;
percelFileDescriptor.close();
picked_image.setImageBitmap(image);
} catch (FileNotFoundException e)
{
System.out.println("File Not Found: " + e.toString());
Toast.makeText(getApplicationContext(),"File not found: "+e.toString(),Toast.LENGTH_LONG).show();
} catch (IOException e)
{
Toast.makeText(getApplicationContext(),"IO Error: "+e.toString(),Toast.LENGTH_LONG).show();
System.out.println("IO Exception: " + e.toString());
}
}
break;
default:
break;
}
}
}
Related
I want capture video from camera Intent and save in app directory (don't save video in Device Gallery) and insert video path into database to load and display in my app
i try in my activity :
public class VideoActivity extends Activity {
private TblVideo TBL_VIDEO;
private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
long date = System.currentTimeMillis();
String string_path = DATABASE_LOCATION + LAST_MOMENT_ID + "_" + date + ".mp4";
File mediaFile = new File(string_path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Button buttonRecording = (Button) findViewById(R.id.photo_btn_take_video);
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
fileUri = Uri.fromFile(mediaFile);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private String SaveMediaFile(int type) {
if (type == MEDIA_TYPE_VIDEO) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mediaFile);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return string_path;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
try {
if (resultCode == RESULT_OK) {
insertVideo();
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
but when go to file directory , video size is 0Kb !! and save into device gallery
How to fix this problem ?
thanks
and try this but app is crash :
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
FileOutputStream fileOutputStream = null;
try {
FileInputStream fileInputStream = new FileInputStream(fileUri.getPath());
fileOutputStream = new FileOutputStream(mediaFile);
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
insertVideo();
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
}
}
i use this and save video file after activity result is OK, save video in directory !
private String SaveMediaFile() {
try {
InputStream in = getContentResolver().openInputStream(fileUri); // Uri
OutputStream out = new FileOutputStream(mediaFile); // file
byte[] buf = new byte[1024];
int len;
assert in != null;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو");
}
return string_path;
}
thanks
How can i get file size after take camera.
I run the code the following results:filesize is 0.I think that the Camera InputStream is writing.But how can I get the real file size?
private void takeCamera(){
file = File.createTempFile("tp_", ".jpg", dir);
filePathCamera = file.getAbsolutePath();
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_CAMERA:
final File file = new File(filePathCamera);
if (!file.exists()) {
result.append("not exists\n");
return;
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePathCamera);
long size = inputStream.available();
result.append("size1:" + size + "\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
// ignore
}
}
break;
}
}
}
In onActivityResult in case REQUEST_CODE_CAMERA: after checking if !file.exists() you can check in else part file.length which will give you size of file.
This is the code i used to record video from an android device in MP4 format. The file is being created but is of 0 bytes size.
Here is my code :-
Button buttonStart;
File newFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent record = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
record.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(record, 5);
}
});
}
protected void initUI(){
buttonStart = (Button) findViewById(R.id.buttonRecord);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 5){
if(resultCode == RESULT_OK){
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Video Captured Successfully...!!", Toast.LENGTH_LONG).show();
}
}
}
I don't understand what has gone wrong.
Can anybody help me ...
Thanks
String strVideoPath=null;//define global variable
to open an Intetn for video recording
void displayCamera() {
File imagesFolder = new File(Environment
.getExternalStorageDirectory(), getResources()
.getString(R.string.app_name) + "foldername");
try {
imagesFolder.mkdirs();
} catch (Exception e) {
}
File f_image = new File(imagesFolder, new Date().getTime() + ".mp4");
Uri uriSavedVideo = Uri.fromFile(f_image);
Intent intent = new Intent(
MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedVideo);
strVideoPath = f_image.getAbsolutePath();
try {
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
catch it on OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111) {
if (resultCode == mActivity.RESULT_OK) {
//do stuff here on success
}else{
strVideoPath=null;
}
}
}
first u need to create a directory
File newFileLocation;
try {
newFileLocation = new File(Environment.getExternalStorageDirectory(), "videoyo");
imagesFolder.mkdirs();
newFile = new File(newFileLocation , "vid" + ".mp4");
} catch (Exception e) {
}
This is my existing code for the crop intent. This works fine on all devices
private void choosePhotoFromCamera() {
System.out.println("choosePhotoFromCamera");
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (getExternalFilesDir(null) == null) {
Log.e(TAG, "No SDcard");
Log.e(TAG,
"Maybe this will work : "
+ Environment.getExternalStorageDirectory());
Toast.makeText(ChooseFromCamera.this, "The app needs SDcard inserted",
Toast.LENGTH_LONG).show();
return;
}
File imagFile = null;
try {
imagFile = File.createTempFile("" + System.currentTimeMillis(),
".jpg", getExternalFilesDir(null));
c= imagFile.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
uriForTempCapturePhoto = Uri.fromFile(imagFile);
String uristring= getPath(this, uriForTempCapturePhoto);
uriForTempCapturePhoto= Uri.parse(uristring);*/
i.putExtra(MediaStore.EXTRA_OUTPUT, uriForTempCapturePhoto);
startActivityForResult(i, TAKE_PHOTO_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
System.out.println("onActivityResult3333333333333333333333");
if (requestCode == TAKE_PHOTO_REQUEST_CODE
|| requestCode == SELECT_PHOTO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Uri uri = null;
if (requestCode == SELECT_PHOTO_REQUEST_CODE) {
uri = intent.getData();
} else if (requestCode == TAKE_PHOTO_REQUEST_CODE) {
uri = uriForTempCapturePhoto;
}
if (uri != null) {
try {
u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), c, null, null));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
}
final Intent intent1 = new Intent(
"com.android.camera.action.CROP");
System.out.println(" uri of the image "+uriForTempCapturePhoto);
intent1.setDataAndType(u, "image/*");
intent1.putExtra("" +"", "true");
intent1.putExtra("aspectX", 1);
intent1.putExtra("aspectY", 1);
intent1.putExtra("outputX", 100);
intent1.putExtra("outputY", 100);
intent1.putExtra("return-data", true);
startActivityForResult(intent1, CUT_PHOTO_REQUEST_CODE);
}
}else{
this.finish();
}
} else if (requestCode == CUT_PHOTO_REQUEST_CODE
|| requestCode == TAKE_GALLERY_REQUEST_CODE) {
if (resultCode == RESULT_OK && intent != null) {
System.out.println("4444444444444444444444444444444");
Bitmap bm = intent.getParcelableExtra("data");
if(bm != null){
System.out.println("Test : " + bm.toString());
}
else
System.out.println("Null Value");
Bitmap bmpCircular = createCircularBitmap(bm);
System.out.println("bmpCircular1111111111111111111"+bmpCircular);
/*if (bmpCircular == null) {
return;
}
String name = null;
String path = Utils.saveBitmap(
ChooseFromCamera.this.getApplicationContext(), name,
bmpCircular);
if (ChooseFromCamera.this == null) {
Log.e(TAG, "called this at wrong time.");
return;
}
if (path != null) {
// sucessfully
System.out.println("choosePhotoFromGallery1111111111111111111"+path);
setContentView(R.layout.main);
ivCamera = (ImageView) findViewById(R.id.iv_camera);
ivAccount = (RoundCornerImageView) findViewById(R.id.iv_account_indicator);
ivAccount.setImageBitmap(bmpCircular);
ivCamera.setVisibility(View.INVISIBLE);
}*/
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bmpCircular.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
//String encoded = "abcdef";
System.out.println("encoded value"+encoded);
ChooseCamera.callKonyFunction(encoded);
this.finish();
}else{
this.finish();
}
}
}
Now when I test it in android M, I am getting the following exception.
java.lang.IllegalArgumentException: mediaStoreUri must be a MediaStore
Uri
To fix this issue insert image with mediastore and try to use the uri as below but this code also fails only in android M. Please help to fix.
if (uri != null) {
try {
u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), c, null, null));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{}
intent1.setDataAndType(u, "image/*");
Now i get only issue with Android M devices . The crop intent returns null in this case
When I recognize text from the ABBYY business card it works. When I try it with a photo I took it failed. It does works on the demo from ABBYY so it's not my hardware.
Does anyone know why this is?
Code I use to take a photo:
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUESTCODE_PHOTO);
if(requestCode == REQUESTCODE_PHOTO){
if( resultCode == Activity.RESULT_OK){
RecognizerManager.recognizeText((Bitmap)data.getExtras().get("data"), this);
}
}
public static void recognizeText(final Bitmap bitmap, final RecognitionCallback listener){
RecognitionConfiguration config = new RecognitionConfiguration();
config.setRecognitionLanguages(Engine.getInstance().getLanguagesAvailableForOcr());
config.setRecognitionMode(RecognitionMode.FULL);
config.setImageProcessingOptions(RecognitionConfiguration.ImageProcessingOptions.FIND_ALL_TEXT);
RecognitionManager recManager = Engine.getInstance().getRecognitionManager(config);
try {
Object o = recManager.recognizeText(bitmap, listener);
Log.i("RESULT!", o.toString());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RecognitionFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I got it to work using this following code.
Photo taking in my RecognizeActivy:
final File photo = new File( Environment.getExternalStorageDirectory(), genPhotoFileName() );
RecognizeActivity.this.imageUri = Uri.fromFile( photo );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra( MediaStore.EXTRA_OUTPUT, imageUri );
startActivityForResult(intent, REQUESTCODE_PHOTO);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUESTCODE_PHOTO){
if( resultCode == Activity.RESULT_OK){
if(this.imageUri != null){
try{
final AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getContentResolver().openAssetFileDescriptor(this.imageUri, "r" );
long imageFileSize = assetFileDescriptor.getLength();
if( imageFileSize == AssetFileDescriptor.UNKNOWN_LENGTH ) {
throw new IOException( "UNKNOWN_LENGTH" );
}
InputStream is = assetFileDescriptor.createInputStream();
byte[] imageData = new byte[(int) imageFileSize];
is.read( imageData );
if(this.bitmap != null){
this.bitmap.recycle();
this.bitmap = null;
System.gc();
}
this.bitmap = BitmapFactory.decodeByteArray( imageData, 0, (int) imageFileSize, new Options() );
RecognizerManager.recognizeText(this.bitmap, this);
} catch(Exception e){
e.printStackTrace();
}
} else{
Log.e("ERROR", "img = null");
}
}
}
}
I'm recycling the bitmap because if I don't I get an OutOfMemory Exception after taking a few photo's.
Photo processing:
public static void recognizeText(final Bitmap bitmap, final RecognitionCallback progressListener){
final RecognitionConfiguration config = new RecognitionConfiguration();
config.setImageResolution(0);
config.setImageProcessingOptions( RecognitionConfiguration.ImageProcessingOptions.PROHIBIT_VERTICAL_CJK_TEXT);
for(RecognitionLanguage e : Engine.getInstance().getLanguagesAvailableForOcr()){
if(e.equals(RecognitionLanguage.English) || e.equals(RecognitionLanguage.Dutch)){
final Set<RecognitionLanguage> languages = EnumSet.noneOf( RecognitionLanguage.class );
languages.add(e);
config.setRecognitionLanguages(languages);
}
}
RecognitionManager recManager = Engine.getInstance().getRecognitionManager(config);
try {
Object o = recManager.recognizeText(bitmap, progressListener);
Log.i("RESULT!", o.toString());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RecognitionFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are implementing RecognitionCallback in the same activity you should implement it first, then call: recognizeText(this.bitmap, this) instead of RecognizerManager.recognizeText(this.bitmap, this); Also don`t forget to implement the 3 methods required: onPrebuiltWordsInfoReady, onRecognitionProgress, onRotationTypeDetected
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUESTCODE_PHOTO){
if( resultCode == Activity.RESULT_OK){
if(this.imageUri != null){
try{
final AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getContentResolver().openAssetFileDescriptor(this.imageUri, "r" );
long imageFileSize = assetFileDescriptor.getLength();
if( imageFileSize == AssetFileDescriptor.UNKNOWN_LENGTH ) {
throw new IOException( "UNKNOWN_LENGTH" );
}
InputStream is = assetFileDescriptor.createInputStream();
byte[] imageData = new byte[(int) imageFileSize];
is.read( imageData );
if(this.bitmap != null){
this.bitmap.recycle();
this.bitmap = null;
System.gc();
}
this.bitmap = BitmapFactory.decodeByteArray( imageData, 0, (int) imageFileSize, new Options() );
// CALL recognizeText(this.bitmap, this); instead of RecognizerManager.recognizeText(this.bitmap, this);
recognizeText(this.bitmap, this);
} catch(Exception e){
e.printStackTrace();
}
} else{
Log.e("ERROR", "img = null");
}
}
}
}