Andoid 调用相机程序获取图片

本文详细介绍了如何在Android应用中通过启动相机程序获取图片,并使用裁剪功能对拍摄完成的图片进行调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Andoid 调用相机程序获取图片

标签: Android


  • 启动相机程序(打开相机程序)
imageUri = Uri.fromFile(outputFile);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,TAKE_PHOTO);

intent传递了一个数据 MediaStore.EXTRA_OUTPUT
API文档:

public static final String EXTRA_OUTPUT

Added in API level 3 The name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video.
指明一个内容接收地址用于存放图片或视频。

  • 拍摄完成的图片裁剪操作
/*使用startActivityForResult启动程序结束后会调用此方法*/
protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode){
            case TAKE_PHOTO:
                if (resultCode==RESULT_OK){
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(imageUri,"image/*");//提供操作数据,要裁剪的图片位置
                    intent.putExtra("scale", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);//图片的保存位置
                    startActivityForResult(intent,CROP_PHOTO);//启动裁剪程序
                }
                break;
            case CROP_PHOTO:
                if (resultCode==RESULT_OK){
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }
}


  • Intent的Data与Type属性
    1. Data属性通常用于向Action属性提供操作的数据,Data属性接受一个Uri对象
    2. Type属性则用于明确指定Data属性的数据类型或MIME类型,但是通常来说,当Intent不指定Data属性时Type属性才会起作用,否则Android系统将会根据Data属性值来分析数据的类型,所以无需指定Type属性。
      API文档:

public Intent setDataAndType (Uri data, String type)
Added in API level 1
(Usually optional) Set the data for the intent along with an explicit MIME data type. This method should very rarely be used – it allows you to override the MIME type that would ordinarily be inferred from the data with your own type given here.
使用的概率非常少,谷歌认为使用这个并没有什么必要。
Note: MIME type and Uri scheme matching in the Android framework is case-sensitive, unlike the formal RFC definitions. As a result, you should always write these elements with lower case letters, or use normalizeMimeType(String) or normalizeScheme() or setDataAndTypeAndNormalize(Uri, String) to ensure that they are converted to lower case.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值