【问题标题】:Android: How to store image from camera and show the in gallery?Android:如何存储来自相机的图像并显示图库?
【发布时间】:2021-01-17 03:51:55
【问题描述】:

我是 Android 新手,我会创建使用相机的应用程序,将相机拍摄的图像存储在设备中并将其显示在图库中?有人对如何做有任何建议吗?现在我已经创建了允许您拍照的活动,但我不知道如何继续保存并在图库中显示从相机拍摄的照片。请帮帮我,我很绝望。在此先感谢大家。

这是我来自 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;
        }
    }

}


【问题讨论】:

标签: android


【解决方案1】:

允许相机和存储权限

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();
        }
    }
}

【讨论】:

  • 您好,首先感谢您的回复。无论如何,我尝试了这段代码,但它没有保存图像,也没有在图库中显示它。这怎么可能?
  • @FrancescoBottiglia 您好,此代码将您的图像保存在您的移动存储中。图库应用程序只需扫描此存储并显示图像或其他媒体文件
  • Okok 但是它不起作用,因为我找不到任何名为“/MyImages /”的文件夹,所以没有保存任何内容。
  • if (file.getParent() != null && !root.isDirectory()) { root.mkdirs(); }else{ Log.e(TAG, "文件夹未创建"); } 并检查是否允许 android 权限
  • 谢谢,但我通过添加一个方法解决了这个问题,该方法负责刷新设备的画廊,因为我无法在那里查看照片
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 2020-03-03
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
相关资源
最近更新 更多