简体   繁体   中英

How to take image from camera show in ImageView without losing its Quality in Android?

I use this simple code for capturing Image from camera. I have found this issue a lot and try many methods but cannot solve this issue. My Image is mostly PDF when i capture it It become unreadable due to worse pixels

 private static final int CAMERA_REQUEST = 1888;
            private ImageView imageView;
            private static final int MY_CAMERA_PERMISSION_CODE = 100;
            ImageView Image;


            private static final int REQUEST_CAPTURE_IMAGE = 100;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_camera_test);
                Image = (ImageView) findViewById(R.id.Image);
                Button camera = (Button) findViewById(R.id.camera);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
                            {
                                requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
                            }
                            else
                            {
                                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(cameraIntent, CAMERA_REQUEST);
                            }
                        }
                    }

                });



            }




 @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
        {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == MY_CAMERA_PERMISSION_CODE)
            {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
                else
                {
                    Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
                }
            }
        }




  @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
            {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                Image.setImageBitmap(photo);
            }
        }

I use this simple code for capturing Image from camera. I have found this issue a lot and try many methods but cannot solve this issue. My Image is mostly PDF when i capture it It become unreadable due to worse pixels

If you need your image in best quality, you need to save it to a file, otherwise you can just access the thumbnail (low res image). I will share how I did it.

Inside your manifest, you need to define a file provider inside application tag, permissions also.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<application...>
...
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="{your package name}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_path" />
    </provider>
</application>

You will also need to make a FileProvider in your res/xml folder. Mine looks like this:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="/storage/emulated/0/Pictures/" path="Pictures/"/>
</paths>

Please do more research, where do you want to save your photos, in my example you can save them only to SD card, but there are more options.

Now, taking photo and saving it.

private var currentPhotoUri = Uri.EMPTY
private var currentPhotoPath
private val requestCode = 123

private fun dispatchTakePictureIntent() {
    Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
        // Ensure that there's a camera activity to handle the intent
        takePictureIntent.resolveActivity(activity?.packageManager!!)?.also {

            createFile()

            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, currentFileUri)
            startActivityForResult(takePictureIntent, requestCode)
        }
    }
}

private fun createFile(): File? {
    val photoFile: File? = try {
        createImageFile()
    } catch (ex: IOException) {
        Log.i("mylog error", "Error creating file: " + ex.toString())
        ex.printStackTrace()
        null
    }
    // Continue only if the File was successfully created
    photoFile?.also {
        val photoURI: Uri = context?.let { context ->
            FileProvider.getUriForFile(
                    context,
                    "{your package name}.fileprovider",
                    it
            )
        } as Uri
        currentPhotoUri = photoURI

    }
    return photoFile
}

private fun createImageFile(): File {
    val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
    val storageDir: File? = context!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    Log.i("mylog", "storage dir = " + storageDir?.absolutePath)
    return File.createTempFile(
            "JPEG_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    ).apply {
        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = absolutePath
    }

}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) 
{
    if (requestCode == requestCode && resultCode == RESULT_OK) {
        val bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),currentPhotoUri)
        val imageView = findViewById(R.id.Image)
        imageView.setImageBitmap(bitmap)
    }
}

That should work. Dont forget to check permissions. You can learn more here .

The object which you have in intent data is a thumbnail of this image. When you capture the photo you should specify path to file. You can also use CameraX API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM