简体   繁体   English

如何从 ImageView 中的相机显示中获取图像而不会失去 Android 中的质量?

[英]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当我捕获它时,我的图像主要是 PDF 由于像素较差,它变得不可读

 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当我捕获它时,我的图像主要是 PDF 由于像素较差,它变得不可读

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.您还需要在 res/xml 文件夹中创建一个 FileProvider。 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.请做更多的研究,你想把照片保存在哪里,在我的例子中,你只能将它们保存到 SD 卡,但还有更多选择。

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.您在意图数据中拥有的 object 是此图像的缩略图。 When you capture the photo you should specify path to file.当您拍摄照片时,您应该指定文件路径。 You can also use CameraX API.您也可以使用 CameraX API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不损失图像质量的情况下完美地将图像放入图像视图中 - How to fit image into the imageview perfectly without losing image quality android 如何将使用设备相机拍摄的图像直接发送到服务器而不丢失其质量,宽度和高度? - How to send the image taken with device camera as it is to server without losing its quality, width and height? 从相机拍摄照片并将其显示到ImageView Android - Take Picture From Camera And Show it to the ImageView Android 如何在Android中压缩图像而不损失质量? - How to compress an image without losing quality in Android? 在 android 中减小图像大小而不会降低其质量 - Decrease image size without losing its quality in android 如何在Android中以原始质量在ImageView上显示大图像文件? - How to show large image file on ImageView with original quality in android? 压缩图像而不会丢失任何质量的android? - Compress image without losing any quality android? 从TextView创建图像(不会丢失质量) - Create an image from a TextView (without losing quality) 从相机捕获图像在Android的ImageView中不显示? - Capture image from camera does not show in ImageView in Android? 如何将我从相机获得的位图保存到SD卡而不会丢失其原始尺寸和质量 - How to save a bitmap that I got from camera, to the sd card without losing it's original size and quality
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM