Android(安卓)调用系统相册选择照片与调用系统相机拍照保存照片并显示在当前界面
效果图
点击图库
选择照片
返回图片
相机与图库操作相同
以下是代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.sun.bluetooth.PicActivity"> <ImageView android:id="@+id/iv_pic" android:src="@mipmap/ic_launcher" android:layout_width="match_parent" android:layout_height="400dp" android:scaleType="centerCrop"/> <Button android:layout_marginTop="16dp" android:id="@+id/btu_select" android:text="图库" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center"/> <Button android:id="@+id/camera" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="相机"/> LinearLayout>LinearLayout>
MainActivity
public class MainActivity extends Activity {
private File mPhotoFile;
private String mPhotoPath;
private Button library;
private Button camera;
private ImageView mImageView;
private static final int REQUEST_SYSTEM_PIC = 1;
private static final int CAMERA_RESULT = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
camera = (Button)findViewById( R.id.camera );
library = (Button) findViewById(R.id.btu_select);
library.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
//打开系统相册
openAlbum();
}
}
});
camera.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent intent = new Intent(“android.media.action.IMAGE_CAPTURE”);//开始拍照
mPhotoPath = getSDPath()+”/”+ getPhotoFileName();//设置图片文件路径,getSDPath()和getPhotoFileName()具体实现在下面
mPhotoFile = new File(mPhotoPath); if (!mPhotoFile.exists()) { mPhotoFile.createNewFile();//创建新文件 } intent.putExtra(MediaStore.EXTRA_OUTPUT,//Intent有了图片的信息 Uri.fromFile(mPhotoFile)); startActivityForResult(intent, CAMERA_RESULT);//跳转界面传回拍照所得数据 } catch (Exception e) { } } } ); mImageView = (ImageView) findViewById(R.id.iv_pic);}public String getSDPath(){ File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在 if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory();//获取跟目录 } return sdDir.toString();}private String getPhotoFileName() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat( "'IMG'_yyyyMMdd_HHmmss"); return dateFormat.format(date) +".jpg";} //打开系统相册private void openAlbum() { Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, REQUEST_SYSTEM_PIC);//打开系统相册}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 1: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { openAlbum(); } else { Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show(); } break; default: }}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //相册照片 if (requestCode == REQUEST_SYSTEM_PIC && resultCode == RESULT_OK && null != data) { if (Build.VERSION.SDK_INT >= 19) { handleImageOnKitkat(data); } else { handleImageBeforeKitkat(data); } } //相机照片 if (requestCode == CAMERA_RESULT) { Bitmap bitmap = BitmapFactory.decodeFile(mPhotoPath, null); mImageView.setImageBitmap(bitmap); }}@TargetApi(19)private void handleImageOnKitkat(Intent data) { String imagePath = null; Uri uri = data.getData(); if (DocumentsContract.isDocumentUri(this, uri)) { //如果是document类型的uri,则通过document id处理 String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docId.split(":")[1]; String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" + "//downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { //如果是content类型的uri,则使用普通方式处理 imagePath = getImagePath(uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { //如果是File类型的uri,直接获取图片路径即可 imagePath = uri.getPath(); } //根据图片路径显示图片 displayImage(imagePath);}private void handleImageBeforeKitkat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath);}private String getImagePath(Uri uri, String selection) { String path = null; //通过uri和selection来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path;}private void displayImage(String imagePath) { if (imagePath != null) { Bitmap bitmap = BitmapFactory.decodeFile(imagePath); mImageView.setImageBitmap(bitmap); } else { Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show(); }}
}
更多相关文章
- Android(安卓)手势 正则匹配图片
- android2.2更新为android2.3
- Android用ImageView显示本地和网上的图片
- 安卓在代码中设置TextView的drawableLeft、drawableRight、drawa
- AndroidManifest.xml的android:name是否带.的区别
- [Android(安卓)Pro] 关于BitmapFactory.decodeStream(is)方法无
- Android:不同drawable文件夹的区别
- android 之 新浪微博
- android 简单比较 两个图片是否一致