调用系统图库和相机

实现:从一小块图片中点击,出现对话框-“从相册中选择”、“拍一张照片”。
裁剪好之后存在sd卡中,并存在服务器端。(注:存在服务器端暂时没有实现)

主布局如下:

<?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:gravity="right"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_photo"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_margin="8dp"
        android:clickable="true"
        android:src="@drawable/actionbar_camera_icon" />

</LinearLayout>

对话框布局如下:

<?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="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="从相册中选择" />

    <Button
        android:id="@+id/btn_take"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="拍一张照片" />

</LinearLayout>

主界面如下:

package com.jackie.app_test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 图库和拍照的界面
 * Created by Administrator on 2016/11/7.
 */
public class GalleryAndTakePhotoActivity extends Activity {


    private Button btn_choose;
    private String imageName;
    private ImageView iv_photo;
    private File cropResultFile;
    private Button btn_take;
    private AlertDialog alertDialog;

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery_takephoto);
        iv_photo = (ImageView)findViewById(R.id.iv_photo);

        //加载对话框视图
        View view_alertdialog = LayoutInflater.from(this).inflate(R.layout.alertdialog_takephoto_gallery,null);
        btn_take = (Button)view_alertdialog.findViewById(R.id.btn_take);
        btn_choose = (Button)view_alertdialog.findViewById(R.id.btn_choose);

        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(view_alertdialog);
        alertDialog = builder.create();

        //为iv_photo注册事件监听
        iv_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.show();
            }
        });

        btn_take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //MediaStore.ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE"
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                imageName = getNowTime() + ".png";
                //拍摄的照片存储路径
                cropResultFile = new File(Environment.getExternalStorageDirectory().getPath(),imageName);
                //存储
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropResultFile));
                startActivityForResult(intent,PHOTO_REQUEST_TAKEPHOTO);
                alertDialog.cancel();
            }
        });

        btn_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent.ACTION_GET_CONTENT="android.intent.action.GET_CONTENT";
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                imageName = getNowTime() + ".png";
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                alertDialog.cancel();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    startPhotoZoom(Uri.fromFile(cropResultFile),320);
                    break;

                case PHOTO_REQUEST_GALLERY :
                    if (data != null){
                        startPhotoZoom(data.getData(), 320);
                    }
                    break;

                case PHOTO_REQUEST_CUT:

                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(cropResultFile.getPath(), opts);

                    //原始图片的宽高
                    int bitmap_w = opts.outWidth;
                    int bitmap_h = opts.outHeight;

                    //获取屏幕信息
                    WindowManager windowManager = getWindowManager();
                    Display display = windowManager.getDefaultDisplay();
                    DisplayMetrics displayMetrics = new DisplayMetrics();
                    display.getMetrics(displayMetrics);
                    //获取屏幕宽高
                    int sw = displayMetrics.widthPixels;
                    int sh = displayMetrics.heightPixels;

                    //计算各宽高比例
                    int sampleW = bitmap_w / sw;
                    int sampleH = bitmap_h / sh;

                    //计算采样因子
                    int sampleSize = (sampleH > sampleW) ? sampleH : sampleW;

                    opts.inJustDecodeBounds = false;
                    opts.inSampleSize = sampleSize;
                    Bitmap bitmap_later = BitmapFactory.decodeFile(cropResultFile.getPath(), opts);
                    iv_photo.setImageBitmap(bitmap_later);
                    break;

            }

        }
    }

    private void startPhotoZoom(Uri uri, int size) {
        //MediaStore.EXTRA_OUTPUT ="output";
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        // true:不返回uri,false:返回uri
        intent.putExtra("return-data", false);
        intent.putExtra("scale",true);
        intent.putExtra("noFaceDetection", false); // 取消人脸识别

        //裁剪后的图片存储的位置
        //注意:此路径将拍照存储的路径覆盖。
        cropResultFile = new File(Environment.getExternalStorageDirectory().getPath(),imageName);
        intent.putExtra("output", Uri.fromFile(cropResultFile));

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    @SuppressLint("SimpleDateFormat")
    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return dateFormat.format(date);
    }
}

千万不要忘了操作sdcard的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
Android调用图库相机可以通过Intent实现,具体步骤如下: 1. 创建一个Intent对象,指定action为ACTION_PICK或ACTION_IMAGE_CAPTURE,分别表示调用图库相机。 ```java Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // 或者 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); ``` 2. 调用startActivityForResult()方法启动Intent。 ```java startActivityForResult(intent, requestCode); ``` 3. 在onActivityResult()方法中获取返回结果,判断requestCode以区分是从图库还是相机返回的结果。 ```java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == REQUEST_CODE_PICK_IMAGE) { // 从图库返回 Uri uri = data.getData(); // 获取图库选中的图片Uri // 处理图片 } else if (requestCode == REQUEST_CODE_CAPTURE_IMAGE) { // 从相机返回 Bitmap bitmap = (Bitmap) data.getExtras().get("data"); // 获取相机拍摄的图片 // 处理图片 } } } ``` 注意事项: 1. 需要在AndroidManifest.xml中添加相应权限: ```xml <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> ``` 2. 调用相机时需要注意Android版本兼容性问题,可以使用FileProvider解决。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值