Android:捕获的图像未显示在图库中(Media Scanner意图不起作用) [英] Android: captured image not showing up in gallery (Media Scanner intent not working)

查看:71
本文介绍了Android:捕获的图像未显示在图库中(Media Scanner意图不起作用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题:我正在开发一个应用程序,用户可以在该应用程序中拍照(附加到帖子),然后将图片保存到外部存储中.我也希望这张照片也显示在图片库中,并且我正在为此使用Media Scanner意图,但是它似乎不起作用.编写代码时,我遵循的是官方的Android开发人员指南,所以我不知道出了什么问题.

I have the following problem: I am working on an app where the user can take a picture (to attach to a post) and the picture is saved to external storage. I want this photo to show up in the pictures gallery as well and I am using a Media Scanner intent for that, but it does not seem to work. I was following the official Android developer guide when writing the code, so I don't know what's going wrong.

我的代码的一部分:

捕获图像的意图:

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(getActivity().getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Toast.makeText(getActivity(), ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

创建文件以保存图像:

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 = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

在视图中显示图像:

private void setPic() {
    // Get the dimensions of the View
    int targetW = 60;
    int targetH = 100;

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    img_added.setImageBitmap(bitmap);
}

广播媒体扫描仪以使图像显示在图库中

Broadcasting a Media Scanner intent to make the image show up in the gallery:

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

返回图像捕获意图后要运行的代码:

Code to run after the Image Capture intent returned:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
        setPic();

        galleryAddPic();
    }
}

我也尝试使用Intent.ACTION_MEDIA_MOUNTED而不是Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,但是在那种情况下,我遇到了权限被拒绝"错误.当我记录传递给该意图的URI时,得到file:///storage/emulated/0/Pictures/JPEG_20150803_104122_-1534770215.jpg,应该没问题.除此之外,其他所有方法(捕获图像,将其保存到外部存储并在视图中显示)均有效,因此我真的不知道出了什么问题.有人有什么主意吗?预先感谢!

I have also tried to use Intent.ACTION_MEDIA_MOUNTED instead of Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, but in that case I got a "permission denied" error. When I log the URI passed to the intent, I get file:///storage/emulated/0/Pictures/JPEG_20150803_104122_-1534770215.jpg, which should be fine. Everything else works (capturing the image, saving it to external storage and displaying it in the view) except for this, so I really don't know what's going wrong. Does anyone have any idea? Thanks in advance!

推荐答案

这取决于此设备Gallery的实现方式.流行的照片应用程序可以接收Intent.ACTION_MEDIA_SCANNER_SCAN_FILE广播,但是有些只能收听Android媒体数据库.

It depends on how this device Gallery implement. Popular photo apps receive Intent.ACTION_MEDIA_SCANNER_SCAN_FILE broadcast but some just listen to Android media database.

或者,您可以同时将图像手动插入MediaStore.

Alternative you can insert a image into the MediaStore manually at the same time.

public final void notifyMediaStoreScanner(final File file) {
        try {
            MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                    file.getAbsolutePath(), file.getName(), null);
            mContext.sendBroadcast(new Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

此外,请确保您的照片不在内部存储之类的private文件夹中,或使用Context.MODE_PRIVATE书写.否则,其他应用程序将无权访问此文件.

Addition, make sure your photo not in a private folder, like internal storage or write with Context.MODE_PRIVATE. Otherwise other apps will not have the permission to access this file.

这篇关于Android:捕获的图像未显示在图库中(Media Scanner意图不起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆