android从摄像头或者图库选择图片,并进行裁剪,可以用来用户头像处理

/**
 * 选择图片的界面,也就底部弹窗的效果,只能单选,同时也要对图片进行裁剪,用户修改头像用
 * 
 * @author JJS
 * 
 */
public class SelectPhotoActivity extends BaseActivity implements
		OnClickListener {
	/** 使用照相机拍照获取图片 */
	private static final int SELECT_PIC_BY_TACK_PHOTO = 1;
	/** 使用相册中的图片 */
	private static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	/** 裁剪图片 */
	private static final int CROP_PHOTO = 3;

	/** 开启相机 */
	@InjectView(R.id.select_tv_take_photo)
	private TextView mTvTackPhoto;
	/** 开启图册 */
	@InjectView(R.id.select_tv_pick_photo)
	private TextView mTvPickPhoto;
	/** 取消 */
	@InjectView(R.id.select_tv_cancel)
	private TextView mTvCancel;
	
	/** 获取到的图片路径 */
	private String mPhotoPath;
	private Uri mPhotoUri;
	/** 头像名称 */
	private static final String IMAGE_FILE_NAME = "image.jpg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_photo);
		Injector.get(this).inject();

		mTvTackPhoto.setOnClickListener(this);
		mTvPickPhoto.setOnClickListener(this);
		mTvCancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.select_tv_take_photo: // 开启相机
			takePhoto();
			break;
		case R.id.select_tv_pick_photo: // 开启图册
			pickPhoto();
			break;
		case R.id.select_tv_cancel: // 取消操作
			this.finish();
			break;
		default:
			break;
		}
	}

	/**
	 * 拍照获取图片
	 */
	private void takePhoto() {
		// 执行拍照前,应该先判断SD卡是否存在
		if (SDCardUtil.isSDCardEnable()) {
			Intent intentFromCapture = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
			/***
			 * 需要说明一下,以下操作使用照相机拍照,拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
			 * 如果不使用ContentValues存放照片路径的话,拍照后获取的图片为缩略图不清晰
			 */
			// 方法一
			// ContentValues values = new ContentValues();
			// mPhotoUri = this.getContentResolver().insert(
			// MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			// intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
			// 方法二
			File path = Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
			File file = new File(path, IMAGE_FILE_NAME);
			//
			showLog(path.toString());
			intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(file));

			startActivityForResult(intentFromCapture, SELECT_PIC_BY_TACK_PHOTO);
		} else {
			showToast("内存卡不存在");
		}
	}

	/***
	 * 从相册中取图片
	 */
	private void pickPhoto() {
		Intent intent = new Intent();
		intent.setType("image/*");// 设置文件类型
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		return super.onTouchEvent(event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			doPhoto(requestCode, data);
		}else{
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 选择图片后,获取图片的路径
	 * 
	 * @param requestCode
	 * @param data
	 */
	private void doPhoto(int requestCode, Intent data) {
		if (requestCode == SELECT_PIC_BY_TACK_PHOTO) {// 从相机拍照后获取图片
			// 判断存储卡是否可以用,可用进行存储
			if (SDCardUtil.isSDCardEnable()) {
				File path = Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
				File tempFile = new File(path, IMAGE_FILE_NAME);
				startPhotoZoom(Uri.fromFile(tempFile));
			} else {
				showToast("未找到存储卡,无法存储照片!");
			}
		} else if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {// 从相册取图片,有些手机有异常情况,请注意
			if (data == null) {
				showToast("选择图片文件出错");
				return;
			}
			mPhotoUri = data.getData();
			if (mPhotoUri == null) {
				showToast("选择图片文件出错");
				return;
			}
			String[] pojo = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(mPhotoUri, pojo, null, null, null);
			if (cursor != null) {
				int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
				cursor.moveToFirst();
				mPhotoPath = cursor.getString(columnIndex);
				if(VERSION.SDK_INT < 14){ //4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
					cursor.close();					
				}
			}
			if (mPhotoPath != null
					&& (mPhotoPath.endsWith(".png")
							|| mPhotoPath.endsWith(".PNG")
							|| mPhotoPath.endsWith(".jpg") || mPhotoPath
								.endsWith(".JPG"))) {
				// mLastIntent.putExtra(KEY_PHOTO_PATH, mPhotoPath);
				startPhotoZoom(mPhotoUri);
			} else {
				showToast("选择图片文件不正确");
			}
		} else if (requestCode == CROP_PHOTO) { // 图片缩放完成后
			if (data != null) {
				setResult(Activity.RESULT_OK, data);
			}
			finish();
		}

	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	private void startPhotoZoom(Uri uri) {
		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", 340);
		intent.putExtra("outputY", 340);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, CROP_PHOTO);
	}
}




/**
 * SD卡相关辅助类
 * 
 * @author JJS
 * 
 */
public class SDCardUtil {

	private SDCardUtil() {
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 判断SDCard是否可用
	 * 
	 * @return
	 */
	public static boolean isSDCardEnable() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/**
	 * 获取SD卡路径
	 * 
	 * @return
	 */
	public static String getSDCardPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator;
	}

	/**
	 * 获取SD卡的剩余容量 单位byte
	 * 
	 * @return
	 */
	public static long getSDCardAllSize() {
		if (isSDCardEnable()) {
			StatFs stat = new StatFs(getSDCardPath());
			// 获取空闲的数据块的数量
			long availableBlocks = (long) stat.getAvailableBlocks() - 4;
			// 获取单个数据块的大小(byte)
			long freeBlocks = stat.getAvailableBlocks();
			return freeBlocks * availableBlocks;
		}
		return 0;
	}

	/**
	 * 获取指定路径所在空间的剩余可用容量字节数,单位byte
	 * 
	 * @param filePath
	 * @return 容量字节 SDCard可用空间,内部存储可用空间
	 */
	public static long getFreeBytes(String filePath) {
		// 如果是sd卡的下的路径,则获取sd卡可用容量
		if (filePath.startsWith(getSDCardPath())) {
			filePath = getSDCardPath();
		} else {// 如果是内部存储的路径,则获取内存存储的可用容量
			filePath = Environment.getDataDirectory().getAbsolutePath();
		}
		StatFs stat = new StatFs(filePath);
		long availableBlocks = (long) stat.getAvailableBlocks() - 4;
		return stat.getBlockSize() * availableBlocks;
	}

	/**
	 * 获取系统存储路径
	 * 
	 * @return
	 */
	public static String getRootDirectoryPath() {
		return Environment.getRootDirectory().getAbsolutePath();
	}

}


<!-- 选取照片的Activity的样式风格,采取对话框的风格 -->
    <style name="AnimBottom" parent="@android:style/Animation">
        <item name="android:windowEnterAnimation">@anim/push_bottom_in</item>
        <item name="android:windowExitAnimation">@anim/push_bottom_out</item>
    </style>
    <style name="DialogStyleBottom" parent="android:Theme.Dialog">
        <item name="android:windowAnimationStyle">@style/AnimBottom</item>
        <!-- 边框 -->  
        <item name="android:windowFrame">@null</item>
        <!-- 是否浮现在activity之上 -->  
        <item name="android:windowIsFloating">false</item>
        <!-- 窗口透明,解决activity启动黑屏的瞬间 -->  
        <item name="android:windowIsTranslucent">true</item>
        <!-- 无标题 -->  
        <item name="android:windowNoTitle">true</item>
        <!-- 背景透明 -->  
        <item name="android:windowBackground">@android:color/transparent</item>
        <!-- 模糊 -->  
       <item name="android:backgroundDimEnabled">true</item>
    </style>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值