0

I have been working on my Photo Editor Android application. After capturing the image from the camera, I am resizing the image since there is a maximum size allowed to save the image in the Gallery/Photos of a phone

Following is the Java Activity code:

package com.example.photoeditor;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class HomeActivity extends AppCompatActivity {
  private AdView mAdView;
  private static final String TAG = "HomeActivity";
  private static final int GALLERY_RESULT = 1;
  private static final int CAMERA_RESULT = 2;
  private static final String FILE_PROVIDER_AUTHORITY = "com.example.photoeditor";
  private static final int CAMERA_PERMISSION_REQ_CODE = 1001;
  private static final int STORAGE_PERMISSION_REQ_CODE = 1002;

  private String mCapturedImagePath;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mAdView = (AdView)findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
  }

  public void openCamera(View view) {
    // check for camera permission if not granted before
    if (ContextCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED) {
      String[] cameraPermission = { CAMERA };
      ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_PERMISSION_REQ_CODE);
    } else {
      dispatchImageCaptureIntent();
    }
  }

  public void openGallery(View view) {
    // check for storage permission if not granted before
    if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
        ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
      String[] storagePermissions = { READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE };
      ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_PERMISSION_REQ_CODE);
    } else {
      dispatchGalleryIntent();
    }
  }

  private void dispatchGalleryIntent() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, GALLERY_RESULT);
  }

  private void dispatchImageCaptureIntent() {
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
      File photoFile = null;
      try {
        photoFile = createImageFile();
      } catch (IOException e) {
        e.printStackTrace();
      }

      if (photoFile != null) {
        Uri photoFileUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);
        Log.d(TAG, "dispatchImageCaptureIntent:photoFileUri: " + photoFile.toString());
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
        startActivityForResult(cameraIntent, CAMERA_RESULT);
      }
    }
  }

  @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
      @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
      case CAMERA_PERMISSION_REQ_CODE:
        if (grantResults[0] == PERMISSION_GRANTED) {
          dispatchImageCaptureIntent();
        } else {
          Toast.makeText(this, "Required camera permission not granted", Toast.LENGTH_SHORT).show();
        }
        break;

      case STORAGE_PERMISSION_REQ_CODE:
        if (grantResults[0] == PERMISSION_GRANTED) {
          dispatchGalleryIntent();
        } else {
          Toast.makeText(this, "Required storage permission not granted", Toast.LENGTH_SHORT)
              .show();
        }
        break;

      default:
        throw new IllegalArgumentException("Unexpected request code");
    }
  }

  private File createImageFile() throws IOException {
    String timeStamp = DateFormat.getDateTimeInstance().format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);
    mCapturedImagePath = image.getAbsolutePath();
    Log.d(TAG, "createImageFile: " + mCapturedImagePath);
    return image;
  }

  private Bundle uriToBundle(Uri imageUri) {
    Bundle bundle = new Bundle();
    bundle.putString(MainActivity.IMAGE_URI, imageUri.toString());
    return bundle;
  }

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
      if (requestCode == GALLERY_RESULT) {
        Uri imageUri = data.getData();
        startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageUri))));
      } else if (requestCode == CAMERA_RESULT) {
          File imageFile = new File(mCapturedImagePath);
          Bitmap image = BitmapFactory.decodeFile(mCapturedImagePath);
          image = Bitmap.createScaledBitmap(image, 100, 100, false);
          ByteArrayOutputStream bytes = new ByteArrayOutputStream();
          image.compress(Bitmap.CompressFormat.JPEG, 60, bytes);

          try {
              File file = new File(Environment.getExternalStorageDirectory() + File.separator + "filename.jpg");
              boolean result;
              result = file.createNewFile();
              if (result) {
                FileOutputStream fo = new FileOutputStream(imageFile);
                fo.write(bytes.toByteArray());
                fo.close();
              }
          } catch(IOException ie) {
              ie.printStackTrace();
          }
      }
    } else {
      Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
    }
  }

  public static Intent getIntent(Context context) {
    return new Intent(context, HomeActivity.class);
  }
}

So when I capture the image and then when the user is taken to edit the application, it doesn't, it takes me back to Home page again after capturing the image

Can you please tell me where am I going wrong ?

Thanks in advance

user2201935
  • 396
  • 1
  • 7
  • 19

1 Answers1

0

You forgot to call start activity on the condition of CAMERA_RESULT block at onActivityResult().

----- Edit 1 -----

After having a conversation with him, the problem is solved it by adding startActivity() on the condition of CAMERA_RESULT block at onActivityResult().

startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageToUploadUri))));

Here's the code I fixed it, see comments in code for more information.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == GALLERY_RESULT) {
                Uri imageUri = data.getData();
                startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageUri))));
            } else if (requestCode == CAMERA_RESULT) {

                //Reducing Image Size
                File imageFile = new File(mCapturedImagePath);
                Bitmap image = BitmapFactory.decodeFile(mCapturedImagePath);
                image = Bitmap.createScaledBitmap(image, 300, 300, false);
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

                //This section is needed as you need to replace the image got from camera with reduced bitmap.
                //So that you just only need to carry URI not the bitmap.
                try {
                    File file = new File(Environment.getExternalStorageDirectory() + File.separator + "filename.jpg");
                    boolean result;
                    result = file.createNewFile();
                    if (result) {
                        FileOutputStream fo = new FileOutputStream(imageFile);
                        fo.write(bytes.toByteArray());
                        fo.close();
                    }
                } catch(IOException ie) {
                    ie.printStackTrace();
                }

                // Here's the main point.
                // You need to start MainActivity as bitmap has been processed.
                startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageToUploadUri))));

            }
        } else {
            Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
        }
    }
  • Thanks, but if this is not against stack overflow rules , can you tell me how bitmap output can be called in startActivity ? – user2201935 Oct 31 '18 at 05:20
  • you already saved as a file, isn't it? Do you mean you want to carry the resized image to another activity? – Zwal Pyae Kyaw Oct 31 '18 at 05:31
  • No, I mean you said that I forgot to call start activity on condition of camera_result block at onActivityResult right , so I am asking how to call that ? – user2201935 Oct 31 '18 at 05:33
  • You need an activity to display the resized image. You can carry it via `intent.putExtra()`. Let's say your next activity is `ImageResultActivity`. Then, `Intent intent = new Intent(this, ImageResultActivity.class); intent.putExtra("BitmapImage", yourbitmap);` and retrieve it on `ImageResultActivity` by `Intent intent = getIntent(); Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");` – Zwal Pyae Kyaw Oct 31 '18 at 05:38
  • mark this as an answer if my works answer your question – Zwal Pyae Kyaw Oct 31 '18 at 06:59
  • My next activity is 'MainActivity'. So this is Intent intent = new Intent(this, MainActivity.class); – user2201935 Oct 31 '18 at 08:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/182842/discussion-between-user2201935-and-zwal-pyae-kyaw). – user2201935 Oct 31 '18 at 08:42