简体   繁体   English

Android:如何存储来自相机的图像并显示画廊?

[英]Android: How to store image from camera and show the in gallery?

I'm new in Android and I would create app that uses camera, store image taken from camera in device and show it in gallery?我是 Android 的新手,我会创建使用相机的应用程序,将相机拍摄的图像存储在设备中并在图库中显示? Anyone have any advice on how to do it?有人对如何做有任何建议吗? For now I have created the activity that allows you to take pictures but I don't know how to proceed to save and show the photos taken from the camera in the gallery.现在我已经创建了允许您拍照的活动,但我不知道如何继续保存并在图库中显示从相机拍摄的照片。 Please help me, I'm very desperate.请帮帮我,我很绝望。 Thanks in advance to everyone.在此先感谢大家。

This is my code from android documentation:这是我来自 android 文档的代码:

public class CamActivity extends AppCompatActivity {

    private ImageView imageView;
    private Button photoButton;
    private String currentPhotoPath;
    private File photoFile = null;

    static final int REQUEST_IMAGE_CAPTURE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_camera);
        imageView =  findViewById(R.id.taken_photo);
        photoButton = findViewById(R.id.btnCaptureImage);

        photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(checkPermissions()) {
                    dispatchTakePictureIntent();
                    galleryAddPic();
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
            imageView.setImageBitmap(myBitmap);
        } else  {
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        }
    }

    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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        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
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                Toast.makeText(CamActivity.this, "error" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.myapp.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private boolean checkPermissions() {
        //Check permission
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            //Permission Granted
            return true;
        } else {
            //Permission not granted, ask for permission
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_IMAGE_CAPTURE);
            return false;
        }
    }

}


allow camera and storage permission允许相机和存储权限

public class CamActivity extends AppCompatActivity {

    private ImageView imageView;
    private Button photoButton;
    private String currentPhotoPath;
    private File photoFile = null;
    private static final String TAG = "CamActivity";
    static final int REQUEST_IMAGE_CAPTURE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.taken_photo);
        photoButton = findViewById(R.id.btnCaptureImage);

        photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                captureImage();
            }
        });
    }


    @SuppressLint("QueryPermissionsNeeded")
    private void captureImage() {
        Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(pictureIntent, 100);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
                saveImage(imageBitmap);
                imageView.setImageBitmap(imageBitmap);
            }
        }
    }

    private void saveImage(Bitmap bitmap) {
        String filename;
        Date date = new Date(0);
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        filename = sdf.format(date);

        try {
            String path = Environment.getExternalStorageDirectory().toString();
            OutputStream outputStream = null;
            File file = new File(path, "/MyImages/"+filename + ".jpg");
            File root = new File(Objects.requireNonNull(file.getParent()));
            if (file.getParent() != null && !root.isDirectory()) {
                root.mkdirs();
            }
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
            outputStream.flush();
            outputStream.close();
            MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

        } catch (Exception e) {
            Log.e(TAG, "saveImage: " + e);
            e.printStackTrace();
        }
    }
}

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

相关问题 如何将相机拍摄的图像存储在图库中? - How to store image captured from camera in gallery? 如何将相机中的图像存储在SQLiteDatabase中并在Android应用程序中显示预览? - How to store image from camera in SQLiteDatabase and show preview In Android Application? Android:将图像从相机存储到数据库并显示 - Android : Store an image from camera to database and the show it 如何在Android Gallery上显示相机? - How to show camera on android gallery? Android一起从图库或相机显示选项中选择图像 - Android chose image from gallery or camera show option together 如何在图库中的imageView上设置图像以及在Android中由相机拍摄的图像? - How to set an image on imageView from the gallery and image taken by camera in Android? 从相机或画廊拍摄图像并在活动中显示 - Take image from camera or gallery and show in activity Android:如何将图像从相机或画廊传递到另一个片段? - Android : How to pass an image from camera or gallery to another fragment? 如何在 Android 7.0 中从相机或图库中选择要裁剪的图像? - How to pick image for crop from camera or gallery in Android 7.0? 如何在Android中制作“从图库或照相机中选择图像” - How to make “Select Image From Gallery or Camera” in Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM