关闭

android 照相和相册中选择照片

标签: android相册 拍照图片
257人阅读 评论(0) 收藏 举报
分类:

很多时候,需要从手机相册或者是照相中获得一张图片,那么就需要调用系统的工具,那么如何做呢?

首先需要给权限,这些权限是必须要有的,如下:

    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />

    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如何调系统的拍照呢,首先去指定一个系统的文件路径,然后调用系统的拍照功能。代码如下:

File outputImg = new File(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);
                try {
                    if (outputImg.exists()){
                        outputImg.delete();
                    }
                    outputImg.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imageUri = Uri.fromFile(outputImg);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

                startActivityForResult(intent,1);

如何去调用系统相册呢,直接去调用系统的相册,代码如下:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "选择图片"), 2);

调用这两个方法后,都会跳到其他界面,其他界面操作完后,这个时候,回调自己的界面,自己的界面需要去获取到传回来的照片,那么我们在
onActivityResult()方法中获取到Bitmap信息
如果是拍照传回来的数据,使用该方法获取bitmap
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri);
如果是相册中传回来的数据,使用该方法获取bitmap
Uri uri = data.getData();
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri);
接下来我给出自己的代码,运行起来更直观。
首先给出photo_dialog.xml,该文件是Dialog需要加载的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical"
              android:layout_marginLeft="20dp"
              android:layout_marginRight="20dp">
    <TextView
        android:id="@+id/photodialog_photograph"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="拍照"
        android:textSize="18dp"
        android:textColor="#4EA9DE"
        android:gravity="center"/>
    <View
        android:id="@+id/findpwd_love_ll"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#919191"
        android:layout_below="@+id/offerhelp_rl_toptitle"/>
    <TextView
        android:id="@+id/photodialog_photoalbum"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="从相册选择"
        android:textSize="18dp"
        android:textColor="#4EA9DE"
        android:gravity="center" />
    <View
        android:id="@+id/findpwd_love_ll2"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#919191"
        android:orientation="horizontal"
        android:layout_below="@+id/offerhelp_rl_toptitle"/>
    <TextView
        android:id="@+id/photodialog_cannel"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="取消"
        android:textSize="18dp"
        android:gravity="center" />

</LinearLayout>
在给出activity_photo.xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button
        android:id="@+id/photo_bt_dialog"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginTop="80dp"
        android:layout_marginRight="24dp"
        android:layout_marginLeft="24dp"
        android:text="点击弹框"
        android:textColor="#ffffff"
        android:textSize="20dp"
        android:background="@color/colorPrimary"/>

    <ImageView
        android:id="@+id/gethelp_im_zhao"
        android:layout_width="150dp"
        android:layout_height="100dp"
        android:scaleType="fitXY"
        android:src="@drawable/love_get8_03"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"/>


</LinearLayout>

在Activity中写下如下代码:
 private AlertDialog mAlertDialog;
    private ImageView mShowPhotoIV;

    public static final String IMAGE_FILE_NAME = "tuoen_image.jpg";
    Uri imageUri;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        mShowPhotoIV = (ImageView) findViewById(R.id.gethelp_im_zhao);

        Button button = (Button) findViewById(R.id.photo_bt_dialog);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择图片方式");
        View view = LayoutInflater.from(this).inflate(R.layout.photo_dialog, null);
        handlerDialog(view);            //处理View中的事件
        builder.setView(view);
        mAlertDialog = builder.create();
        mAlertDialog.setCanceledOnTouchOutside(false);      //设置点击其他位置Dialog不消失
        mAlertDialog.show();                                //显示Dialog
    }

    private void handlerDialog(View view){
        TextView photographTV = (TextView) view.findViewById(R.id.photodialog_photograph);          //拍照
        photographTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File outputImg = new File(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);
                try {
                    if (outputImg.exists()){
                        outputImg.delete();
                    }
                    outputImg.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imageUri = Uri.fromFile(outputImg);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

                startActivityForResult(intent,1);
                mAlertDialog.dismiss();
            }
        });
        TextView photoalbumTV = (TextView) view.findViewById(R.id.photodialog_photoalbum);          //从相册中选一张照片
        photoalbumTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "选择图片"), 2);

                mAlertDialog.dismiss();
            }
        });
        TextView cancelTV = (TextView) view.findViewById(R.id.photodialog_cannel);
        cancelTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAlertDialog.dismiss();     //取消dialog
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        if (requestCode == 1){
            try {
                Bitmap bitmap = decodeToSpecifySize(BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)), 540, 450);
                mShowPhotoIV.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }else if (requestCode == 2){
            Uri uri = data.getData();
            try {
                Bitmap bitmap = decodeToSpecifySize(BitmapFactory.decodeStream(getContentResolver().openInputStream(uri)), 540, 450);
                mShowPhotoIV.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 对图片进行裁剪的代码
     * @param bitmap
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public Bitmap decodeToSpecifySize(Bitmap bitmap, int reqWidth, int reqHeight) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = (float) reqWidth / w;
        float scaleHeight = (float) reqHeight / h;
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }
这里再运行之前,一定不要忘了添加权限。



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7992次
    • 积分:311
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:2篇
    • 译文:0篇
    • 评论:1条
    最新评论