Image loses it's original result when passing it to another activity

杀马特。学长 韩版系。学妹 提交于 2019-11-27 09:50:25

The method which you have used will not work on all the devices above marshmallow. Follow this,

add this in your manifest.xml

 <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="yourpackagename.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_path"/>
    </provider>

create provider_path in xml folder of your resources.

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="/storage/emulated/0" path="."/>
</paths>

then add this in your activity, declare a global variable

private Uri mUri;
private static final String CAPTURE_IMAGE_FILE_PROVIDER = "com.yourpackagename.fileprovider";
 private void takePicture() {
    File file = null;
    try {
        file = createImageFile();
        mUri = FileProvider.getUriForFile(context,
                CAPTURE_IMAGE_FILE_PROVIDER, file);

        Log.d("uri", mUri.toString());
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(cameraIntent, REQUEST_CAMERA_STORAGE);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CAMERA_STORAGE) {
        if (resultCode == RESULT_OK) {
            if (mUri != null) {
                String profileImageFilepath = mUri.getPath().replace("//", "/");
                sendImage(profileImageFilepath);
            }
        } else {
            Toast.makeText(context, "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
        }
    }
}

this is createImageFile()

private File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "APPNAME-" + timeStamp + ".png";
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),
            "FOLDERNAME");
    File storageDir = new File(mediaStorageDir + "/Images");
    if (!storageDir.exists()) {
        storageDir.mkdirs();
    }
    File image = new File(storageDir, imageFileName);
    return image;
}

and finally, pass profileImageFilepath to our next activity to display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!