camera and gallery intent to get image and copy in

2019-07-14 13:49发布

问题:

I am trying to upload photo from camera, gallery and google photos. without camera code gallery and google photos is working properly but when I am adding the code for camera Intent is not returning the result as -1 and gallery and google photos is also not working properly :: it is copying the image to another folder but need to exit the app to show the image again in imageview. here is my code

final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("Select Picture");
                    builder.setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals("Take Photo"))
                            {
                                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                imageUri = getImageUri();
                                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                                       Intent cameraIntent = getCameraIntent();
                                    startActivityForResult(cameraIntent, 2);

                            }
                            else if (options[item].equals("Choose from Gallery"))
                            {
                                if (Build.VERSION.SDK_INT <= 19) {
                                    Intent intent = new Intent();
                                    intent.setType("image/*");
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
                                } else if (Build.VERSION.SDK_INT > 19) {
                                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);


                                }
                            }
                            else if (options[item].equals("Cancel")) {
                                dialog.dismiss();
                            }
                        }
                    });
                    builder.show();

here is code for activity result

 public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    String selectedImagePath=null;
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && null != data) {
        Uri selectedImageUri = data.getData();
        selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
        decodeFile(selectedImagePath);
    }else if(requestCode==2&&resultCode==getActivity().RESULT_OK &&data!=null){
        Uri selectedImageUri = data.getData();
        selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
        decodeFile(selectedImagePath);
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
        Log.d("uri",selectedImagePath+":"+selectedImageUri);
    }
}

code to copy the image

  try {
        File sd = Environment.getExternalStorageDirectory();
        File directory = Environment.getExternalStorageDirectory();
        String destinationPath = Environment.getExternalStorageDirectory().toString() + "/IASFolders/"+Configuration.empcode+".jpg";
        if (sd.canWrite()) {
            File source= finalFile;
            File destination= new File(destinationPath);
            if (source.exists()) {
                FileChannel src = new FileInputStream(source).getChannel();
                FileChannel dst = new FileOutputStream(destination).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }else {
                FileChannel src = new FileInputStream(source).getChannel();
                FileChannel dst = new FileOutputStream(destination).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

after dst.close() it is getting out but not copying anything

回答1:

Try this...(Tested)

    private static final int PICK_IMAGE = 1;
    private static final int REQUEST_CAMERA = 2;

          final String[] items = new String[]{"Camera", "Gallery"};   
    new AlertDialog.Builder(getActivity()).setTitle("Select Picture")
    .setItems(options, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Camera")) {
              Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, REQUEST_CAMERA);
               } else if (items[item].equals("Gallery")) {
                if (Build.VERSION.SDK_INT <= 19) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
                } else if (Build.VERSION.SDK_INT > 19) {
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
                }
            }else if (options[item].equals("Cancel")) {
                                dialog.dismiss();
                            }
        }
    }).show();

code for activity result

     @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
                Uri selectedImageUri = data.getData();
                String selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
                decodeFile(selectedImagePath);
            } else if (requestCode == REQUEST_CAMERA && resultCode == getActivity().RESULT_OK && null != data) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                profileImage.setImageBitmap(photo);

                // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                Uri tempUri = getImageUri(getActivity().getApplicationContext(), photo);

                // CALL THIS METHOD TO GET THE ACTUAL PATH
                File finalFile = new File(getRealPathFromURI(tempUri));
                decodeFile(finalFile.toString());
            }
        }
public String getRealPathFromURIForGallery(Uri uri) {
        if (uri == null) {
            return null;
        }
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return uri.getPath();
    }

    public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public String getRealPathFromURI(Uri uri) {
        Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }