Android App中捕获的图像未保存在手机中

时间:2018-10-20 09:09:42

标签: android photoeditorsdk

嗨,Stack Overflow团队,

下面是PhotoEditor Android应用的Java代码,用于捕获图像或从“图库”中选择照片,然后在手机中编辑和保存图像。

以下是MainActivity.java文件:

package com.example.photoeditor;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import com.adobe.creativesdk.aviary.AdobeImageIntent;

public class MainActivity extends AppCompatActivity {
  public static final String IMAGE_URI = "IMAGE_URI_KEY";

  private static final String TAG = "MainActivity";
  private static final int IMAGE_EDITOR_RESULT = 1;

  private ImageView mEditedImageView;

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

    mEditedImageView = (ImageView) findViewById(R.id.edited_image_view);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      Uri imageUri = Uri.parse(getIntent().getExtras().getString(IMAGE_URI));
      Intent imageEditorIntent = new AdobeImageIntent.Builder(this).setData(imageUri).build();
      startActivityForResult(imageEditorIntent, IMAGE_EDITOR_RESULT);
      finish(); // Comment this out to receive edited image
    }
  }

  // Do something with the edited image
  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case IMAGE_EDITOR_RESULT:
          Uri editedImageUri = data.getParcelableExtra(AdobeImageIntent.EXTRA_OUTPUT_URI);
          Log.d(TAG, "editedImageUri: " + editedImageUri.toString());
          Bundle extra = data.getExtras();
          if (extra != null) {
            boolean changed = extra.getBoolean(AdobeImageIntent.EXTRA_OUT_BITMAP_CHANGED);
            Log.d(TAG, "Image edited: " + changed);
            if (changed) {
              mEditedImageView.setImageURI(editedImageUri);
            }
          }
          break;

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

  public static Intent getIntent(Context context, Bundle bundle) {
    Intent intent = new Intent(context, MainActivity.class);
    if (bundle != null) {
      intent.putExtras(bundle);
    }
    return intent;
  }
}

以下是HomeActivity.java文件:

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.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;

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 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);
  }

  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();
    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) {
    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) {
        File imageFile = new File(mCapturedImagePath);
        Uri imageUri = Uri.fromFile(imageFile);
        startActivity(MainActivity.getIntent(this, uriToBundle(imageUri)));
      }
    } else {
      Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
    }
  }

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

问题是,从应用程序捕获并编辑照片后,我面临的问题是,当我保存图像时,照片没有保存到手机的任何位置,但显示“正在保存...”。 但是保存后,应用会自动退出 当从手机中的图库中编辑照片时,保存照片效果很好。保存问题仅适用于通过此应用程序相机拍摄的照片。

有人可以提供解决方案吗?

预先感谢

1 个答案:

答案 0 :(得分:0)

尝试此操作以保存图像

/**
     * Save Bitmap file
     *
     * @param finalBitmap bitmap to store
     * @param folderName  dst folder
     * @param fileName    dst filename
     * @return Absolute path of file.
     */

    public static String saveFileInSDCard(Context context, Bitmap finalBitmap, String folderName, String fileName, Bitmap.CompressFormat compressFormat) {

            if (context == null) {
                return null;
            }
            File file = new File(makeDirectory(folderName) + File.separator + fileName + ".png");
            if (file.exists()) {
                Log.i("fileUtils", "Exists?? " + file.exists()
                        + " && " + file.delete());
                Log.i("fileUtils", "Exists?? " + file.exists());
            }

            //to compress bitmap before save
            //Bitmap finalBitmap = BitmapUtils.compressSampleBitmap(bitmap,1024);

            try {

                FileOutputStream out = new FileOutputStream(file);

                finalBitmap.compress(compressFormat, 100, out);
                out.flush();
                out.close();
                Log.i(TAG, "Saved: " + file.getAbsolutePath());

                /* Update gallery app */
                MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()},
                        null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                                Log.i(TAG, "Scanned " + path);
                            }
                        });

                return file.getAbsolutePath();
            } catch (Throwable e) {
                e.printStackTrace();
                Log.e(TAG, "Error: " + e.getMessage());
                return null;
            }
        }


public static String makeDirectory(String folderName) {

        File myDir = new File(root + "/" + folderName);
        if (!myDir.exists()) {
            Log.i(TAG, "Making Folder ->" + myDir.getName());
            //will create only single dir
            //myDir.mkdir();

            //will create all required directory specified in the path
            myDir.mkdirs();
        }
        return myDir.getAbsolutePath();
    }