How to recognize landmarks using Firebase ML kit? - java

I'm creating an application for recognizing landmarks.
When the image is recognized, the result should fall to onSuccess, but instead comes to onFailure.
The following message is displayed in the Log:
If you have not set up billing, please go to the Firebase Console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan= true
If you are specifying a debug API Key override and turning on API Key restrictions, make sure the restrictions are set up correctly.
When I click on the link I see the following page:
https://login.corp.google.com/request?s=firebase.corp.google.com:443/uberproxy/&d=https://firebase.corp.google.com/u/0/project/_/overview%3FpurchaseBillingPlan%3Dtrue%26upxsrf%3DAKKYJRc2HD6ROcy9V9DxnYxw-pd8yGnml-oEi37m5hKhkWurWQ:1557057663745&maxAge=1200&authLevel=2000000&keyIds=X-q,k02
What will I need to to do?
public class RecognizeLandmarks extends AppCompatActivity {
EditText mResultEt;
ImageView mPreviewIv;
TextView tvLName, tvLiD, tvLConfidence, tvLlatitude, tvLlongitude;
public static final int CAMERA_REQUEST_CODE = 200;
public static final int STORAGE_REQUEST_CODE = 400;
public static final int IMAGE_PIC_GALLERY_CODE = 1000;
public static final int IMAGE_PIC_CAMERA_CODE = 1001;
private static final String TAG = "MyLog";
String cameraPermission[];
String storagePermission[];
Uri image_uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recognize_landmarks);
androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle("Click image button to insert Image");
mResultEt = findViewById(R.id.resultEt);
mPreviewIv = findViewById(R.id.imageIv);
tvLName = findViewById(R.id.tvLName);
tvLiD = findViewById(R.id.tvLiD);
tvLConfidence = findViewById(R.id.tvLConfidence);
tvLlatitude = findViewById(R.id.tvLlatitude);
tvLlongitude = findViewById(R.id.tvLlongitude);
//camera permission
cameraPermission = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//storage permission
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflate menu
getMenuInflater().inflate(R.menu.menu_recognize_text, menu);
return true;
}
//handle actionbar item clicks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId( );
if (id == R.id.addImage) {
showImageImportDialog( );
}
if (id == R.id.settings) {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show( );
}
return super.onOptionsItemSelected(item);
}
private void showImageImportDialog() {
// items to display in dialog
String[] items = {" Camera", " Gallery"};
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Select Image");
dialog.setItems(items, new DialogInterface.OnClickListener( ) {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//camera option clicked
/*for os Marshmallow and above we need to ask runtime permission for camera and storage*/
if (!checkCameraPermission()) {
//camera permission not allowed, request it
requestCameraPermission();
} else {
//permission allowed, take picture
pickCamera();
}
}
if (i == 1) {
//gallery option clicked
if (!checkStoragePermission()) {
//storage permission not allowed, request it
requestStoragePermission();
} else {
//permission allowed, take picture
pickGallery();
}
}
}
});
dialog.create().show();
}
private void pickGallery() {
//intent to pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
//set intent type to image
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PIC_GALLERY_CODE);
}
private void pickCamera() {
//intent to take image from camera, it will also be save to storage to get high quality image
ContentValues values = new ContentValues( );
values.put(MediaStore.Images.Media.TITLE, "NewPic"); //title of the picture
values.put(MediaStore.Images.Media.DESCRIPTION, "Image to text"); //description
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PIC_CAMERA_CODE);
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestCameraPermission() {
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_REQUEST_CODE);
}
private boolean checkCameraPermission() {
/*Check camera permission and return the result
* in order to get high quality image we have to save image to external storage first
* before inserting to image view that`s why storage permission will also be required */
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickCamera();
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
case STORAGE_REQUEST_CODE:
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickGallery( );
}
else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//got image from camera or gallery
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PIC_GALLERY_CODE) {
//got image from gallery now crop it
CropImage.activity(data.getData( ))
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
if (requestCode == IMAGE_PIC_CAMERA_CODE) {
//got image from camera crop it
CropImage.activity(image_uri)
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
}
//get cropped image
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result1 = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result1.getUri( ); // get image uri
//set image to image view
mPreviewIv.setImageURI(resultUri);// past image in iV
//get drawable bitmap for text recognition
BitmapDrawable bitmapDrawable = (BitmapDrawable) mPreviewIv.getDrawable( );
Bitmap bitmap = bitmapDrawable.getBitmap( );
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionCloudDetectorOptions options =
new FirebaseVisionCloudDetectorOptions.Builder( )
.setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
.setMaxResults(15)
.build( );
FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance( )
.getVisionCloudLandmarkDetector(options);
Task<List<FirebaseVisionCloudLandmark>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionCloudLandmark>>( ) {
#Override
public void onSuccess(List<FirebaseVisionCloudLandmark> firebaseVisionCloudLandmarks) {
// Task completed successfully
// ...
for(FirebaseVisionCloudLandmark landmark : firebaseVisionCloudLandmarks) {
//Rect bounds = landmark.getBoundingBox();
String landmarkName = landmark.getLandmark( );
tvLName.setText(landmarkName);
String entityId = landmark.getEntityId( );
tvLiD.setText(entityId);
float confidence = landmark.getConfidence( );
tvLConfidence.setText(Float.toString(confidence));
// Multiple locations are possible, e.g., the location of the depicted
// landmark and the location the picture was taken.
for(FirebaseVisionLatLng loc : landmark.getLocations( )) {
double latitude = loc.getLatitude( );
tvLlatitude.setText(Double.toString(latitude));
double longitude = loc.getLongitude( );
tvLlongitude.setText(Double.toString(longitude));
}
}
}
})
.addOnFailureListener(new OnFailureListener( ) {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
// ...
Log.d(TAG,e.getMessage());
Toast.makeText(RecognizeLandmarks.this, "Recognizing Failed", Toast.LENGTH_SHORT).show( );
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
//if there is any error show it
Exception error = result1.getError( );
Toast.makeText(this, "" + error, Toast.LENGTH_SHORT).show( );
}
}
}
}
Result
D/MyLog: If you haven't set up billing, please go to Firebase console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan=true. If you are specifying a debug Api Key override and turned on Api Key restrictions, make sure the restrictions are set up correctly

ML Kit's landmark detection does not run on the device itself, but uses Google Cloud Vision. For this reason your project needs to be on a paid plan, before you can use landmark detection. The first 1000 calls are free, after which you will be charged for additional calls.

Related

take photo but not OCR: android studio

I combined the two Java codes, but I have a problem: when I take a picture and then I want to read the text with this picture, it writes the text of the program-assigned image (not taken photo).
The problem is the combination of commands, which I can not sort. Always read the original image (ImageView is installed with a Bitmap test image).
I tried many times but could not order.
P.S I do not want to save the captured image.
Thanks in advance for the feedback.
my Java code:
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888; ///////
private ImageView imageView;///
private static final int MY_CAMERA_PERMISSION_CODE = 100;////
////////////
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}/////////////
ImageView imageview;
Button btnProcess;
EditText txtView, txtVieww;
Bitmap photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.image_view);////
Button photoButton = (Button) this.findViewById(R.id.button1);////
imageview = findViewById(R.id.image_view);
btnProcess = findViewById(R.id.btnProcess);
txtView = findViewById(R.id.txtView);
txtVieww = findViewById(R.id.txtVieww);
photo = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.newyt);
imageview.setImageBitmap(photo);
/////
photoButton.setOnClickListener(v -> {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
///////
btnProcess.setOnClickListener(v -> {
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
txtView.setText(R.string.error_prompt);
txtVieww.setText(R.string.error_prompt);
} else {
Frame frame = new Frame.Builder().setBitmap(photo).build();
SparseArray<TextBlock> items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append("/");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
final String substringi = strBuilder.substring(0, 10).replaceAll("\\s+", "");
final String substringg = substringi.substring(0, 5);
txtView.setText(substringi);
txtVieww.setText(substringg);
}
});
}
}

onactivityresult() is deprecated in android fragment

I search on google for onactivityresult() is deprecated. but my problem was not solve . here is the code of fragment
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length >0 ){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
else {
Toast.makeText(getActivity(), "Please enable camera & storage permission first ", Toast.LENGTH_SHORT).show();
}
}
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION,"Temp Description");
// put image uri
image_uri = requireActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// intent tom start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
// pick from gallery
Intent galleryIntent = new Intent(Intent .ACTION_PICK);
galleryIntent.setType("Images/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
}
Kotlin - Below code instead of startActivityForResult deprecation
this method gives the result itself and returns a value.
val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
when (result.resultCode) {
Activity.RESULT_OK -> {
// logic
}
else -> {
// logic
}
}
}

CropActivity doesn't open after picking image

I tired to do same as in https://www.simplifiedcoding.net/crop-image-android-tutorial/. Pick image from gallary and after crop it. But when i'm included it to my fragment it's open gallary but after doesn't show crop activity. But when i did the same directly in activity its work!
My fragment onViewCreated
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SetupUI(view);
SetupProfile();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
FragmentAdapterProfile adapter = new FragmentAdapterProfile(getActivity(), getActivity().getSupportFragmentManager());
// Set the adapter onto the view pager
pager.setAdapter(adapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.profileTabs);
tabLayout.setupWithViewPager(pager);
tabLayout.getTabAt(0).setText("About");
tabLayout.getTabAt(1).setText("Setting");
tabLayout.getTabAt(2).setText("Post");
changeavatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onSelectImageClick(v);
}
});
}
The picking
public void onSelectImageClick(View view) {
CropImage.startPickImageActivity((Activity) context);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(context, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(context, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
avatar.setImageURI(result.getUri());
Toast.makeText(context, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(context, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(context, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Start crop image activity for the given image.
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.setAspectRatio(1,1)
.start((Activity) context);
}
So i sloved this problem do the next.
I just created secondary Activity (empty) and call crop function in activity after it's work. Problem was in Contexts and Actvities.

How can save camera photo in a file of mobile device?

There is camera codes in my project that another developer who wrote. It takes photo by the device camera but it doesn't save photo in a file of device. It must to save the photo in a file of mobile device. I post here java class and other codes that is related with camera. How can save the photo in device?
SendMessagePage.java
public class SendMessagePage extends BaseActivity {
private static final int CAMERA_RQ = 6969;
private static final int PERMISSION_RQ = 84;
File saveDir = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
}
final MaterialCamera materialCamera =
new MaterialCamera(this)
.saveDir(saveDir)
.showPortraitWarning(true)
.allowRetry(true)
.defaultToFrontFacing(true)
.allowRetry(true)
.autoSubmit(false)
.labelConfirm(R.string.mcam_use_video);
LinearLayout takePhoto = (LinearLayout) findViewById(R.id.take_photo);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
if (1 == 2) {
}
ActivityCompat.requestPermissions(SendMessagePage.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 23
);
}
}
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
materialCamera
.stillShot() // launches the Camera in stillshot mode
.labelConfirm(R.string.mcam_use_stillshot);
materialCamera.start(CAMERA_RQ);
}
});
}
private String readableFileSize(long size) {
if (size <= 0) return size + " B";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups))
+ " "
+ units[digitGroups];
}
private String fileSize(File file) {
return readableFileSize(file.length());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Received recording or error from MaterialCamera
if (requestCode == CAMERA_RQ) {
if (resultCode == RESULT_OK) {
final File file = new File(data.getData().getPath());
Toast.makeText(
this,
String.format("Saved to: %s, size: %s", file.getAbsolutePath(), fileSize(file)),
Toast.LENGTH_LONG)
.show();
} else if (data != null) {
Exception e = (Exception) data.getSerializableExtra(MaterialCamera.ERROR_EXTRA);
if (e != null) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(
this,
"Videos will be saved in a cache directory instead of an external storage directory since permission was denied.",
Toast.LENGTH_LONG)
.show();
}
}
Define this in your class
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
Uri picUri;
File imagefile;
Use the below code for capturing picture. The picture is saved in DCIM folder
takePicture.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureName = getPictureName();
imagefile = new File(pictureDirectory, pictureName);
picUri = Uri.fromFile(imagefile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
imageView.setImageURI(picUri);
}
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
nameOfFile=timestamp + ".jpg";
return timestamp + ".jpg";
}
NOTE: This code is working and has no errors as i have used this code in one of my projects. It has been extracted from code of mine.

How to crop two different images in the same activity with different parameters in Android?

I am using this Crop library by SoundCloud. Selecting one imageview, slecting image, cropping and showing the result in the imageview works fine. But now I am trying to do it with two different imageviews with different specifications. I am not getting any errors nor am I seeing any results. Here's what I have tried:
//My click listeners
regCoverPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
});
regUserProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
});
//Handling the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK) {
beginCropProfile(data.getData());
}else if(requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK){
beginCropCover(data.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(requestCode, resultCode, data);
}
}
private void beginCropProfile(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).withAspect(ASPECT_X, ASPECT_Y).start(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
private void beginCropCover(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
private void handleCrop(int requestCode, int resultCode, Intent result) {
if (requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK) {
regCoverPhoto.setImageURI(Crop.getOutput(result));
mCoverPhotoUri = Crop.getOutput(result);
uploadCoverToStorage();
Log.d(TAG,"ResultCover: " + Crop.getOutput(result).toString());
}else if(requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK){
regUserProfile.setImageURI(Crop.getOutput(result));
mProfilePhotoUri = Crop.getOutput(result);
uploadProfileToStorage();
Log.d(TAG,"ResultProfile: " + Crop.getOutput(result).toString());
} else if (resultCode == Crop.RESULT_ERROR) {
Snackbar.make(getView(), Crop.getError(result).getMessage(), Snackbar.LENGTH_LONG).show();
}
}
I haven't used this library particularly, but custom request codes seem to be the problem.
Use different request codes for picking and cropping (total of 4 request codes) as you will need to handle them differently, and update onActivityResult(), handleCrop() to reflect that.
See https://gist.github.com/vibinr/fcf54c5e7ab63b9184432cc44c9a1494
List item
Here is a complete code of the images selection to crop and uploading to server using rest client with retrofit library Here few variables are used extra as for my use please ignore them
Also i'm using these library inside gradel
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
compile 'com.squareup.retrofit:retrofit:1.6.1'
And inside Mainfrest i have specifed this as <activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:screenOrientation="portrait" />
side2Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_side_2";
image_number_5 = "image_side_2";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_back";
image_number_6 = "image_back";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
if (image_name.equals("image_front")) {
image.setImageURI(result.getUri());
} else if (image_name.equals("image_top")) {
topImage.setImageURI(result.getUri());
} else if (image_name.equals("image_bottom")) {
bottomImage.setImageURI(result.getUri());
} else if (image_name.equals("image_side_1")) {
side1Image.setImageURI(result.getUri());
} else if (image_name.equals("image_side_2")) {
side2Image.setImageURI(result.getUri());
} else if (image_name.equals("image_back")) {
backImage.setImageURI(result.getUri());
}
cropped = result.getUri();
File path = getExternalCacheDir();
new File(String.valueOf(path)).mkdir();
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name22 = dateFormat.format(new Date());
// String helloWorld = cropped.toString();
// String hhhh=helloWorld.substring(helloWorld.indexOf(":")+1,helloWorld.indexOf("/"));
// String name="snehal_go";
savedFileDestination = new File(imagePath, name22 + ".jpg");
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("Webmirchi..", Context.MODE_PRIVATE);
String ALLOWED_CHARACTERS = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789qwertyuiopasdfghjklzxcvbnm";
Random generator = new Random();
randomStringBuilder = new StringBuilder();
int randomLength = 10;
for (int i = 0; i < randomLength; i++) {
randomStringBuilder.append(ALLOWED_CHARACTERS.charAt(generator.nextInt(ALLOWED_CHARACTERS.length())));
}
// Create imageDir
mypath = new File(directory, sessionMail + "-" + ProductId + ".jpg");
FileOutputStream fos = null;
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropped);
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
Log.i("File", mypath.toString());
if (image_name.equals("image_front")) {
uploadImage_front();
} else if (image_name.equals("image_top")) {
uploadImage_top();
} else if (image_name.equals("image_bottom")) {
uploadImage_bottom();
} else if (image_name.equals("image_side_1")) {
uploadImage_side1();
} else if (image_name.equals("image_side_2")) {
uploadImage_side2();
} else if (image_name.equals("image_back")) {
uploadImage_back();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(false)
.setMinCropWindowSize(600, 600)
.setAspectRatio(2, 2)
.setRequestedSize(500, 500)
.start(this);
}
Please refer the following url.This may help you. "https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/"
I'm not good in english...
// took extra int
static int a=0;
private void onClickData() {
cover_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=1;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
author_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=2;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==1){
// change the value again
a=0;
}
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==2){
// change the value again
a=0;
}
}

Categories