The photo lose its quality when it appears into the ImageView

后端 未结 2 1065
南方客
南方客 2021-01-28 07:10

excuse me for any grammatical errors.

I made an application that allow you to take a picture and after you clicked \"Ok\", the picture appear in an ImageView. Now, I don

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-28 07:33

    Just copy paste the whole class:

    public class CameraFragment extends android.support.v4.app.Fragment{   
    
        String mCurrentPhotoPath;
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            final int MyVersion = Build.VERSION.SDK_INT;
            if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
                if (!checkIfAlreadyhavePermission_new()) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    if (!checkIfAlreadyhavePermission()) {
                        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
                    } else {
                        try {
                            dispatchTakePictureIntent();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                try {
                    dispatchTakePictureIntent();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return inflater.inflate(R.layout.fragment_camera,container,false);
        }
    
        ImageView SkimmedImageImg;
        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            SkimmedImageImg = (ImageView)view.findViewById(R.id.SkimmedImg);
        }
    
        static final int REQUEST_IMAGE_CAPTURE = 1;
    
        private void dispatchTakePictureIntent() throws IOException {
            CameraFragment cameraFragment = this;
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // Ensure that there's a camera activity to handle the intent
            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    return;
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    Uri photoURI = FileProvider.getUriForFile(getActivity(),
                            BuildConfig.APPLICATION_ID + ".provider",
                            createImageFile());;
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                    cameraFragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                }
            }
    
        }
    
        private boolean checkIfAlreadyhavePermission() {
            int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
            return result == PackageManager.PERMISSION_GRANTED;
        }
    
        private boolean checkIfAlreadyhavePermission_new() {
            int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
            return result == PackageManager.PERMISSION_GRANTED;
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == REQUEST_IMAGE_CAPTURE) {
                    Uri imageUri = Uri.parse(mCurrentPhotoPath);
                    File file = new File(imageUri.getPath());
                    Glide.with(getActivity())
                         .load(file)
                         .into(SkimmedImageImg);
    
                    // ScanFile so it will be appeared on Gallery
                    MediaScannerConnection.scanFile(getActivity(),
                            new String[]{imageUri.getPath()}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                public void onScanCompleted(String path, Uri uri) {
                                }
                            });
                }
            }
    
        }
    
        private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM), "Camera");
            File image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
    
            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            return image;
        }
    
    
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            switch (requestCode) {
                case 1: {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if (!checkIfAlreadyhavePermission()) {
                            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
                        } else {
                            try {
                                dispatchTakePictureIntent();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        Toast.makeText(getActivity(), "NEED CAMERA PERMISSION", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
    
                case 2: {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        try {
                            dispatchTakePictureIntent();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(getActivity(), "NEED STORAGE PERMISSION", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
                // other 'case' lines to check for other
                // permissions this app might request
            }
        }
    
    }
    

    If you are getting error while Fragment loading in MainActivity, just use getSupportFragmentManager():

     FragmentManager fm = getSupportFragmentManager();
    

提交回复
热议问题