简体   繁体   English

在Android中通过意图使用相机时遇到问题

[英]Facing an issue with using camera by intent in Android

I want to take a picture and store it in a folder with the name Medit via my app. 我想拍照并通过我的应用程序将其存储在名为Medit的文件夹中。 When my app starts, it should be able to pull all the pictures from this folder and display it directly. 当我的应用启动时,它应该能够从该文件夹中提取所有图片并直接显示。 So the data storage path must be set and stored as part of the app. 因此,必须设置数据存储路径并将其存储为应用程序的一部分。 Here is what I have done so far 这是我到目前为止所做的

 public void CaptureImage(){
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mediaStorageDir =new File(Environment.getExternalStorageDirectory(),"MyAppName");
        mUri =Uri.fromFile(mediaStorageDir+"IMG"+System.currentTimeMillis() + ".jpg");

        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            super.onActivityResult(requestCode, resultCode, data);
            Bitmap bm = BitmapFactory.decodeFile(mUri.getPath());
            imgVIew.setImageBitmap(bm);
           }else Log.d("capture", "FAILED");}

Issue is, irrespective what i change mUri to the picture is being stored in DCIM/ camera images with the default naming convention. 问题是,无论我将图片的mUri更改为如何使用默认命名约定存储在DCIM /相机图像中。 In the onActivityResult I am capturing the image. 在onActivityResult中,我正在捕获图像。 Issue is Im not able to comtrol where it is being stored and as what name. 问题是我无法控制其存储位置和名称。 I need to 我需要

1) Capture an image via intent, store it in a location with a custom name. 1)通过意图捕获图像,并将其存储在具有自定义名称的位置。

2) Everytime the app opens, it should go to that same storage location and pull out the pictures and display them one by one. 2)每次打开该应用程序时,它都应转到相同的存储位置并拉出图片并逐一显示。

irrespective what i change mUri to the picture is being stored in DCIM/ camera images with the default naming convention 无论我将图片的mUri更改为什么,都将使用默认命名约定存储在DCIM /摄像机图像中

Most likely, that is a bug in that camera app. 这很可能是该相机应用程序中的错误。 Most camera apps will honor EXTRA_OUTPUT properly. 大多数相机应用都会正确使用EXTRA_OUTPUT However, there is no enforcement mechanism to ensure that a camera app will honor EXTRA_OUTPUT . 但是,没有强制机制可以确保照相机应用程序尊重EXTRA_OUTPUT

However, please do not use string concatenation to create a file path, and make sure that you create your directories. 但是,请不要使用字符串串联来创建文件路径,并确保您创建了目录。 IOW, replace: IOW,更换:

mediaStorageDir =new File(Environment.getExternalStorageDirectory(),"MyAppName");
mUri =Uri.fromFile(mediaStorageDir+"IMG"+System.currentTimeMillis() + ".jpg");

with: 与:

mediaStorageDir=new File(Environment.getExternalStorageDirectory(),"MyAppName");
mediaStorageDir.mkdirs();
mUri=Uri.fromFile(new File(mediaStorageDir, "IMG"+System.currentTimeMillis() + ".jpg"));

It is possible that changing this code will make your app more compatible with this particular camera app, but there are no guarantees that all camera apps will behave as you wish. 更改此代码可能会使您的应用程序与该特定的相机应用程序更加兼容,但是不能保证所有相机应用程序的行为均符合您的期望。

I need to... 我需要...

Your code is written to give you what you want. 编写您的代码是为了给您想要的东西。 However, you are invoking a third-party app with the ACTION_IMAGE_CAPTURE Intent . 但是,您正在使用ACTION_IMAGE_CAPTURE Intent调用第三方应用程序。 There are thousands of camera apps, both pre-installed and available for download from the Play Store and elsewhere. 数以千计的相机应用程序已预先安装,并且可以从Play商店和其他地方下载。 Many will have properly-working ACTION_IMAGE_CAPTURE implementations. 许多将具有可以正常工作的ACTION_IMAGE_CAPTURE实现。 Some will not. 有些不会。

Either: 要么:

  • Detect that the image is not at your desired path and let the user know that their camera app is broken. 检测图像不在所需路径上,并让用户知道其相机应用程序已损坏。 Then, suggest that they install some third-party camera app that you have tested. 然后,建议他们安装一些经过测试的第三方相机应用程序。 Or, 要么,

  • Stop using ACTION_IMAGE_CAPTURE and work with the camera APIs directly, though this is rather difficult. 停止使用ACTION_IMAGE_CAPTURE并直接使用相机API,尽管这很困难。

Your pictures are being save in default path because the path you are providing is wrong. 图片正在保存在默认路径中,因为您提供的路径错误。 Use the following code. 使用以下代码。

File mediaStorageDir =new File(Environment.getExternalStorageDirectory(),"MyAppName");

    if(!mediaStorageDir.exists())
        mediaStorageDir.mkdir();

    Uri mUri = Uri.fromFile(new File(mediaStorageDir.getAbsolutePath() + "/IMG" + System.currentTimeMillis() + ".jpg"));
    LogHelper.LogI("path", mUri.getPath());

Please try th following code it's working for me. 请尝试以下代码,它对我有用。

public class CaptureImage extends Activity {

private static final int PICK_CAMERA_IMAGE = 2;

ImageView img;
Button btn;

private Uri mImageCaptureUri;

public static String userPicPath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_capture_image);

    img = (ImageView) findViewById(R.id.activity_capture_image_img);
    btn = (Button) findViewById(R.id.button1);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat(
                    "yyyyMMdd_HHmmss", Locale.US);

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory()
                    + "/" + Constants.IMAGE_DIRECTORY_NAME, "img_"
                    + dateFormatter.format(new Date()).toString() + ".png");
            userPicPath = file.getPath();
            mImageCaptureUri = Uri.fromFile(file);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
            startActivityForResult(intent, PICK_CAMERA_IMAGE);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_CAMERA_IMAGE && resultCode == RESULT_OK) {

        Log.d("CaptureImage", mImageCaptureUri.toString());

        Bitmap bitmapProfile = getBitmap(userPicPath, this);
        img.setImageBitmap(bitmapProfile);

    }
}

public static Bitmap getBitmap(String path, Context context) {
    Uri uri = Uri.fromFile(new File(path));
    InputStream in = null;
    ContentResolver mContentResolver = context.getContentResolver();
    try {
        // final int IMAGE_MAX_SIZE = 2048;
        final int IMAGE_MAX_SIZE = 1024;
        in = mContentResolver.openInputStream(uri);

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(in, null, o);
        in.close();

        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(
                    2,
                    (int) Math.round(Math.log(IMAGE_MAX_SIZE
                            / (double) Math.max(o.outHeight, o.outWidth))
                            / Math.log(0.5)));
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        in = mContentResolver.openInputStream(uri);
        Bitmap b = BitmapFactory.decodeStream(in, null, o2);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG, 25, stream);
        in.close();

        return b;
    } catch (FileNotFoundException e) {
        Log.e("CaptureImage", "file " + path + " not found");
    } catch (IOException e) {
        Log.e("CaptureImage", "file " + path + " not found");
    }
    return null;
}

} }

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

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