android拍照与读取相册

先创建选择拍照与读取相册的对话框

布局xml

选择对话框dialog_takephoto_selectimage.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:gravity="center"    android:background="@mipmap/updatebg">    <TextView        android:id="@+id/id_textViewTakePhoto"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="@string/take_photo"        android:textSize="18sp"        android:gravity="center"        android:layout_weight="1"        android:drawablePadding="10dp"        android:drawableTop="@mipmap/takephoto"/>    <TextView        android:id="@+id/id_textViewSelectImage"        android:layout_width="0dp"        android:gravity="center"        android:layout_height="wrap_content"        android:text="@string/select_image"        android:layout_weight="1"        android:textSize="18sp"        android:drawablePadding="10dp"        android:drawableTop="@mipmap/album"/></LinearLayout>

选择对话框类

选择对话框类TakePhotoOrSelectImageDialog :

/** * //选择照片或者拍照的对话框 */public class TakePhotoOrSelectImageDialog {    private Context mContext;    private TakePhotoOrSelectImageInterface mListener;    public TakePhotoOrSelectImageDialog(Context context){        mContext = context;        mListener = (TakePhotoOrSelectImageInterface)mContext;    }    public void showDialog(){        View view = View.inflate(mContext, R.layout.dialog_takephoto_selectimage, null);        TextView textViewTakePhoto = (TextView) view.findViewById(R.id.id_textViewTakePhoto);        TextView textViewSelectImage = (TextView) view.findViewById(R.id.id_textViewSelectImage);        final Dialog dialog = new Dialog(mContext, R.style.alert_dialog);        dialog.setContentView(view);       /* Window dialogWindow = dialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); DisplayMetrics d = mContext.getResources().getDisplayMetrics(); // 获取屏幕宽、高用 lp.width = (int) (d.widthPixels * 0.9); // 高度设置为屏幕的0.9 dialogWindow.setAttributes(lp);*/        dialog.show();        textViewTakePhoto.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mListener.takePhoto();                dialog.dismiss();            }        });        textViewSelectImage.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mListener.selectImage();                dialog.dismiss();            }        });    }    public interface TakePhotoOrSelectImageInterface {        public void takePhoto();//拍照按钮        public void selectImage();//相册选择图片        }}

新建一个类,implements TakePhotoOrSelectImageDialog.java接口

    /* 图片文件 */    private static final String IMAGE_FILE_NAME = "temp_image.jpg";    private static final String IMAGE_SCROP_FILE_NAME = "temp_scrop_image.jpg";   /* 请求识别码 */    private static final int CODE_GALLERY_REQUEST = 1;    private static final int CODE_CAMERA_REQUEST = 2;    private static final int CODE_RESULT_REQUEST = 3;        textViewAdd.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                TakePhotoOrSelectImageDialog takePhotoOrSelectImageDialog = new TakePhotoOrSelectImageDialog(NewSmartActivity.this);                takePhotoOrSelectImageDialog.showDialog();            }        });    }    // 从本地相册选取图片    private void choseHeadImageFromGallery() {        /**Intent intentFromGallery = new Intent(); // 设置文件类型 intentFromGallery.setType("image/*"); intentFromGallery.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);*/         Intent intentFromGallery =  new Intent(                Intent.ACTION_PICK,                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);        // 设置文件类型        intentFromGallery.setType("image/*");        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);    }    // 启动手机相机拍摄照片    private void choseHeadImageFromCameraCapture() {        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        // 判断存储卡是否可用,存储照片文件        if (sdcardEnable()) {            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri                    .fromFile(new File(Environment                            .getExternalStorageDirectory(), IMAGE_FILE_NAME)));        }        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        // 用户没有进行有效的设置操作,返回        if (resultCode == RESULT_CANCELED) {            Toast.makeText(getApplication(), "处理照片失败", Toast.LENGTH_LONG).show();            return;        }        switch (requestCode) {            case CODE_GALLERY_REQUEST:                cropRawPhoto(data.getData());                break;            case CODE_CAMERA_REQUEST:                if (sdcardEnable()) {                    File tempFile = new File(                            Environment.getExternalStorageDirectory(),                            IMAGE_FILE_NAME);                    cropRawPhoto(Uri.fromFile(tempFile));                } else {                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG)                            .show();                }                break;            case CODE_RESULT_REQUEST:                if (data != null) {                    setImageToHeadView();                }                break;        }    }    /** * 裁剪原始的图片 */    public void cropRawPhoto(Uri uri) {        //上传照片为默认图片尺寸        int[] heightAndWidth=PublicMethod.getImageWidthAndHeight(NewSmartActivity.this,R.mipmap.defaultsmart);        Intent intent = new Intent("com.android.camera.action.CROP");        intent.setDataAndType(uri, "image/*");        // 设置裁剪        intent.putExtra("crop", "true");        // aspectX , aspectY :宽高的比例        intent.putExtra("aspectX", 1);        intent.putExtra("aspectY", 1);        // outputX , outputY : 裁剪图片宽高,取默认图片的三倍大小,否则图片太小        intent.putExtra("outputX", heightAndWidth[0]*3);        intent.putExtra("outputY", heightAndWidth[1]*3);        intent.putExtra("return-data", true);        File file = new File(Environment                .getExternalStorageDirectory(), IMAGE_SCROP_FILE_NAME);        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));        startActivityForResult(intent, CODE_RESULT_REQUEST);    }    /** * 提取保存裁剪之后的图片数据,并设置头像部分的View */    private void setImageToHeadView() {        try {            Bitmap bitmap =                    new LoadBigImage().decodeSampledBitmapFromByte(getBytesFromInputStream(new FileInputStream(Environment                            .getExternalStorageDirectory() + "/" + IMAGE_SCROP_FILE_NAME)), 150, 150);            LayoutInflater inflater = LayoutInflater                    .from(getApplication());            View v = inflater.inflate(R.layout.dialog_show_iamge, null);            ImageView imageView1 = (ImageView) v.findViewById(R.id.id_imageShow);            imageView1.setImageBitmap(bitmap);            AlertDialog.Builder builder = new AlertDialog.Builder(NewSmartActivity.this);            builder.setTitle("选择操作");            builder.setView(v);            builder.setNegativeButton("上传", new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int which) {                }            });            builder.setPositiveButton("取消", null);            builder.create().show();        } catch (Exception e) {            e.printStackTrace();        }    }    /** * 检查设备是否存在SDCard */    public static boolean sdcardEnable() {        String state = Environment.getExternalStorageState();        if (state.equals(Environment.MEDIA_MOUNTED)) {            // 有存储的SDCard            return true;        } else {            return false;        }    }    //定义一个根据图片url获取InputStream的方法    public static byte[] getBytesFromInputStream(InputStream is) throws IOException {        ByteArrayOutputStream outstream = new ByteArrayOutputStream();        byte[] buffer = new byte[1024]; // 用数据装        int len = -1;        while ((len = is.read(buffer)) != -1) {            outstream.write(buffer, 0, len);        }        outstream.close();        // 关闭流。        return outstream.toByteArray();    }//拍照按钮    @Override    public void takePhoto() {        choseHeadImageFromCameraCapture();    }    //选择照片按钮    @Override    public void selectImage() {        choseHeadImageFromGallery();    }

处理大图片的方法

   /** * 加载大尺寸图片 */public class LoadBigImage {    private  int calculateInSampleSize(BitmapFactory.Options options,  int reqWidth, int reqHeight) {        // 源图片的高度和宽度        final int height = options.outHeight;        final int width = options.outWidth;        int inSampleSize = 1;        if (height > reqHeight || width > reqWidth) {            // 计算出实际宽高和目标宽高的比率            final int heightRatio = Math.round((float) height / (float) reqHeight);            final int widthRatio = Math.round((float) width / (float) reqWidth);            // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高            // 一定都会大于等于目标的宽和高。            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;        }        return inSampleSize;    }    public  Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeResource(res, resId, options);        // 调用上面定义的方法计算inSampleSize值        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);        // 使用获取到的inSampleSize值再次解析图片        options.inJustDecodeBounds = false;        return BitmapFactory.decodeResource(res, resId, options);    }    public  Bitmap decodeSampledBitmapFromByte( byte[] data, int reqWidth, int reqHeight) {        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeByteArray(data, 0, data.length, options);        // 调用上面定义的方法计算inSampleSize值        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);        // 使用获取到的inSampleSize值再次解析图片        options.inJustDecodeBounds = false;        return  BitmapFactory.decodeByteArray(data, 0, data.length, options);    }    public  Bitmap decodeSampledBitmapFromFile( String filename, int reqWidth, int reqHeight) {        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeFile(filename, options);        //BitmapFactory.decodeByteArray(data, 0, data.length,options);        // 调用上面定义的方法计算inSampleSize值        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);        // 使用获取到的inSampleSize值再次解析图片        options.inJustDecodeBounds = false;        return  BitmapFactory.decodeFile(filename, options);    }}

更多相关文章

  1. Android中滑屏初探 ---- scrollTo 以及 scrollBy方法使用说明
  2. Android异步加载图像小结 (含线程池,缓存方法)
  3. android上一些方法的区别和用法的注意事项
  4. android WebView 图片缩放功能小结
  5. Android实现下载文件功能的方法
  6. Android 主流图片库Picasso Glide Fresco对比分析
  7. Android 通讯录中用到的关于按名字首字母排序方法
  8. Android中的常用的对话框

随机推荐

  1. android 怎么实现启动页提前加载webView
  2. android截取屏幕图
  3. Android 国码选择 country code
  4. android圆形图片显示效果,带边框
  5. 自定义ProgressBar的样式失效
  6. Android(安卓)数据库的简单使用
  7. android listview 自动加载
  8. Android中Activity之间访问互传参数
  9. 转:Android之通信录中的联系人操作
  10. Android实现圆角弹框功能