private void selectPhoto() { CharSequence[] items = { "相册", "相机" }; new AlertDialog.Builder(this).setTitle("选择图片来源") .setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == SELECT_PICTURE) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 2); } else { // 拍照我们用Action为MediaStore.ACTION_IMAGE_CAPTURE, // 有些人使用其他的Action但我发现在有些机子中会出问题,所以优先选择这个 Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 1); } } }).create().show(); }
/** * 图片处理 * @param image * @return */ private Bitmap comp(Bitmap image) { // 获取这个图片的宽和高 int width = image.getWidth(); int height = image.getHeight(); // 定义预转换成的图片的宽度和高度 int newWidth = 200; int newHeight = 200; // 计算缩放率,新尺寸除原始尺寸 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 创建操作图片用的matrix对象 Matrix matrix = new Matrix(); // 缩放图片动作 matrix.postScale(scaleWidth, scaleHeight); // //旋转图片 动作 //matrix.postRotate(90); // 创建新的图片 Bitmap resizedBitmap = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true); // compressImage(bitmap);//压缩好比例大小后再进行质量压缩 return resizedBitmap; }
图片处理根据需要。
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { return; } if (data != null) { // 取得返回的Uri,基本上选择照片的时候返回的是以Uri形式,但是在拍照中有得机子呢Uri是空的,所以要特别注意 Uri mImageCaptureUri = data.getData(); // 返回的Uri不为空时,那么图片信息数据都会在Uri中获得。如果为空,那么我们就进行下面的方式获取 if (mImageCaptureUri != null) { Bitmap image; try { // 这个方法是根据Uri获取Bitmap图片的静态方法 image = MediaStore.Images.Media.getBitmap( this.getContentResolver(), mImageCaptureUri); if (image != null) { Drawable drawable = new BitmapDrawable(comp(image)); imageViews.get(flag).setBackgroundDrawable(drawable); } } catch (Exception e) { e.printStackTrace(); } } else { Bundle extras = data.getExtras(); if (extras != null) { // 这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片 Bitmap image = (Bitmap) extras.get("data"); ; if (image != null) { Drawable drawable = new BitmapDrawable(comp(image)); imageViews.get(flag).setBackgroundDrawable(drawable); } } } } }
imageviews.get(flag)是一个imageView