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
Related
I have a profile picture concept in my app. User has options to upload an image from camera or gallery in the app but the problem is the image is being uploaded to some devices not all. Mainly the problem occurs with Android version 8 & 9. I tried almost everything but failed to achieve. Please help.
Code:
dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_image_upload);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
TextView txtTakePhoto = (TextView) dialog.findViewById(R.id.txtTakePhoto);
TextView txtPictureFromGallery = (TextView) dialog.findViewById(R.id.txtPictureFromGallery);
ImageView imgClose = (ImageView) dialog.findViewById(R.id.imgClose);
imgClose.setOnClickListener(this);
txtTakePhoto.setOnClickListener(this);
txtPictureFromGallery.setOnClickListener(this)
Code for take photo from camera:
case R.id.txtTakePhoto:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
{
cameraIntent();
}
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, PHONE_PERMISSION_CODE);
}
} else {
cameraIntent();
}
break;
Code for take photo from gallery:
case R.id.txtPictureFromGallery:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
{
imageBrowse();
}
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PHONE_PERMISSION_CODE);
}
} else {
imageBrowse();
}
break;
Pending code for image uploading :
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST) {
onSelectFromGalleryResult(data);
} else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
//
if (requestCode == 2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri DbsUri = data.getData();
fileDbs = FilePath.getPath(getActivity(), DbsUri);
File f1 = new File(fileDbs);
edtCertificatesValue.setText(f1.getName());
Log.e("tag", "filedbs" + fileDbs);
} else if (requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri picUri = data.getData();
filePath = FilePath.getPath(getActivity(), picUri);
File f2 = new File(filePath);
edtIdentityDocumentValue.setText(f2.getName());
Log.e("tag", "filePath" + filePath + " " + f2.getName());
} else if (requestCode == 4 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri picUri = data.getData();
fileAddress = FilePath.getPath(getActivity(), picUri);
File f3 = new File(fileAddress);
edtProofOfAddressValue.setText(f3.getName());
Log.e("tag", "fileAddress" + fileAddress);
} else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri CvUri = data.getData();
fileCvPath = FilePath.getPath(getActivity(), CvUri);
File f4 = new File(fileCvPath);
edtCurriculumVitaeValue.setText(f4.getName());
Log.e("tag", "fileCvPath" + fileCvPath);
//
}
//
// } else
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
bm = null;
File imageFile = getTempFile(getActivity());
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
boolean isCamera = (data == null ||
data.getData() == null ||
data.getData().toString().contains(imageFile.toString()));
if (isCamera) { /* CAMERA */
selectedImageUri = Uri.fromFile(imageFile);
} else { /* ALBUM */
selectedImageUri = data.getData();
}
bm = getImageResized(getActivity(), selectedImageUri);
int rotation = getRotation(getActivity(), selectedImageUri, isCamera);
bm = rotate(bm, rotation);
ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
byte[] byteImage = bytes1.toByteArray();
encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);
imgProfile.setImageBitmap(bm);
Uri picUri = data.getData();
Log.e("TAG", "onSelectFromGalleryResult: " + bm);
fileImagePath = getPath(picUri);
if (fileImagePath != null) {
try {
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
private String getPath(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getActivity(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
// new code
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
byte[] byteImage = bytes1.toByteArray();
encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Log.d("TAG", "onActivityResult: " + Uri.fromFile(destination));
try {
rotateImageIfRequired(thumbnail, getActivity(), Uri.fromFile(destination));
} catch (Exception e) {
e.printStackTrace();
}
Log.d("TAG", "thumbnail: " + thumbnail);
imgProfile.setImageBitmap(thumbnail);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes1.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fileImagePath = destination.toString();
if (fileImagePath != null) {
try {
// execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.some_error_occured), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(getActivity(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(getActivity(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
API hit Code:
private void execMultipartPost() throws Exception {
RequestBody requestBody;
pBar.setVisibility(View.VISIBLE);
final HashMap<String, String> loggedDetail = sessionManager.getLoggedDetail();
HashMap<String, String> params = new HashMap<String, String>();
String api_token = loggedDetail.get("api_token");
if (filePath != null) {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
fileBody = RequestBody.create(MediaType.parse(contentType), file);
filename = "file_" + System.currentTimeMillis() / 1000L;
Log.e("TAG", "filename: " + filename);
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", filename + ".jpg", fileBody)
.addFormDataPart("name", edtName.getText().toString())
.addFormDataPart("user_id", loggedDetail.get("id"))
.addFormDataPart("email", edtEmailValue.getText().toString())
.addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
.addFormDataPart("phone", edtPhoneNumber.getText().toString())
.addFormDataPart("type", loggedDetail.get("type"))
.addFormDataPart("address", edtAddressValue.getText().toString())
.addFormDataPart("gender", edtGenderValue.getText().toString())
.addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())
.build();
} else {
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", "")
.addFormDataPart("name", edtName.getText().toString())
.addFormDataPart("user_id", loggedDetail.get("id"))
.addFormDataPart("email", edtEmailValue.getText().toString())
.addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
.addFormDataPart("phone", edtPhoneNumber.getText().toString())
.addFormDataPart("type", loggedDetail.get("type"))
.addFormDataPart("address", edtAddressValue.getText().toString())
.addFormDataPart("gender", edtGenderValue.getText().toString())
.addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())
.build();
}
okhttp3.Request request = new okhttp3.Request.Builder()
.url(Constants.EDIT_PROFILE_DATA)
.post(requestBody)
.addHeader("Authorization", "Bearer " + loggedDetail.get("api_token"))
.build();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(150, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
pBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Yes, you need to configure the FileProvider. In your app's manifest, add a provider to your application:
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
...
</application>
Make sure that the authorities string matches the second argument to getUriForFile(Context, String, File). In the meta-data section of the provider definition, you can see that the provider expects eligible paths to be configured in a dedicated resource file, res/xml/file_paths.xml. Here is the content required for this particular example:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
Read the android documentation https://developer.android.com/training/camera/photobasics
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.
I have 2 buttons on an "upload image" page for users to upload an image to a web service. One is for selecting an image that is on your device, the other for taking a photo with your camera.
thisFragment.findViewById(R.id.btnChooseImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Assert.assertNotNull("file uri not null before firing intent", mFileUri);
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//this is the file that the camera app will write to
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
thisFragment.findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Assert.assertNotNull("file uri not null before firing intent", mFileUri);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//this is the file that the camera app will write to
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
btnTakePhoto works fine when it loads an ImageView with the result when I TAKE a photo, but when I CHOOSE a photo using the other button the imageView is blank...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data != null) {
if(data.getData() != null) {
Log.v(LOG_TAG, "intent data: " + data.getData().toString());
}
if(data.getAction() != null) {
Log.v(LOG_TAG, "intent action: " + data.getAction().toString());
}
if(data.getExtras() != null) {
Log.v(LOG_TAG, "intent extras: " + data.getExtras().toString());
}
}
Assert.assertNotNull("file uri in onActivityResult", mFileUri);
Log.v(LOG_TAG, "stored file name is " + mFileUri.toString());
File file = getFileFromUri();
if(file != null) {
Bitmap bm = decodeSampledBitmapFromFile(file, 500, 500);
imgMain.setImageBitmap(bm);
}else{
imgMain.setImageBitmap(null);
}
} else {
parentActivity.finish();
}
}
private File getFileFromUri() {
if(mFileUri != null) {
try {
URI uri;
if(mFileUri.toString().startsWith("file://")){
//normal path
uri = URI.create(mFileUri.toString());
} else {
//support path
uri = URI.create("file://" + mFileUri.toString());
}
File file = new File(uri);
if (file != null) {
//if (file.canRead()) {
return file;
//}
}
} catch (Exception e) {
return null;
}
}
return null;
}
I noticed that when I hit this line of code:
if (file.canRead()) {
return file;
}
file.canRead() is TRUE when I take a picture, but FALSE when I CHOOSE a picture. When I step through and look at the value of the "uri" variable, here they are:
file:///storage/emulated/0/Pictures/IMG_20150916_141518.jpg - this works
file:///storage/emulated/0/Pictures/IMG_20150916_141854.jpg - this doesn't work
any idea what's going on here?
UPDATE: tried using the InputStream approach from ContentResolver, but the bitmap still can't be displayed:
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = parentActivity.getContentResolver().openInputStream(selectedImage);
}catch (FileNotFoundException e){
Log.v(LOG_TAG, "cant load file " + mFileUri.toString());
}
Bitmap bm = BitmapFactory.decodeStream(imageStream);
imgMain.setImageBitmap(bm);
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");
}
}
}
}