Android 图片拍照上传、本地上传

来源:互联网 发布:暗黑破坏神2数据库 编辑:程序博客网 时间:2024/04/30 11:34

1.拍照

(1)指定一个照片的存储路径,方便在onActivityResutl中使用

String name = System.currentTimeMillis() + ".jpg";String path = Environment.getExternalStorageDirectory() + "/image/" + name;
(2)打开相机

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(path)));//这个path就是上面指定好的context.startActivityForResult(intent, REQUEST_TAKE_PHOTO);
2.图库

(1)打开图库

Intent intent;intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);context.startActivityForResult(intent, REQUEST_OPEN_ALBUM);

如果使用 intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT);那么在4.4的系统中onActivityResult获取到的Uri处理起来比较麻烦,需要针对不同的系统进行不同的操作,见http://blog.csdn.net/tempersitu/article/details/20557383。

3.onActivityResult中的处理

protected void onActivityResult(int requestCode, int resultCode, Intent data) {<span style="white-space:pre"></span>super.onActivityResult(requestCode, resultCode, data);switch (requestCode) {case Constant.TAKE_PHOTO_ACTIVITY_FOR_RESULT_CODE:// 拍照
<span style="white-space: pre;"></span>//Bitmap bitmap = (Bitmap)data.getExtras().get("data");
<span style="white-space:pre"></span>//因为打开相机时指定了uri,所以此处得到的data为空。如果不指定uri,这里得到的是缩略图
<span style="white-space:pre"></span>//这里使用上面指定好的图片路径path对图片进行上传处理break;case Constant.ALBUM_ACTIVITY_FOR_RESULT_CODE:// 相册Uri uri = data.getData();<span style="white-space:pre"></span>String[] proj = { MediaStore.Images.Media.DATA };<span style="white-space:pre"></span>Cursor cursor = ((Activity) context).managedQuery(uri, proj, null,null, null);<span style="white-space:pre"></span>int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);<span style="white-space:pre"></span>cursor.moveToFirst();<span style="white-space:pre"></span>String path = cursor.getString(column_index);
<span style="white-space:pre"></span>//根据path上传图片break;<span style="white-space:pre"></span>}
}
0 0