赞
踩
修改布局文件中代码:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Button
- android:id="@+id/take_photo"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Take Photo"/> //用来打开摄像头进行拍照
-
- <ImageView
- android:id="@+id/picture"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"/> //将拍到的图片显示出来
- </LinearLayout>
编写调用摄像头的具体逻辑。修改活动文件:
public class MainActivity extends AppCompatActivity { public static final int TAKE_PHOTO = 1; private ImageView picture; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button takePhoto = (Button) findViewById(R.id.take_photo); picture = (ImageView) findViewById(R.id.picture); takePhoto.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ File outputImage = new File(getExternalCacheDir(),"output_image.jpg"); //创建了一个File对象,用于存放摄像头拍下的图片,并将它保存在SD卡的应用缓存目录下,用getExternalCacheDir()得到目录 try{ if(outputImage.exists()){ outputImage.delete(); } outputImage.createNewFile(); }catch (IOException e) { e.printStackTrace(); } if(Build.VERSION.SDK_INT>=24){ //若设备系统版本低于Android7.0,就调用Uri的fromFile()将File对象转换成Uri对象(表示着图片的本地真实路径) imageUri = FileProvider.getUriForFile(MainActivity.this,"com/example.cameraalbumtest.fileprovider",outputImage);//否则就调用FileProvider的getUriForFile() }else{ imageUri = Uri.fromFile(outputImage); 方法将File对象转换成一个封装过的Uri对象 } Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");//将这个Intent的action指定为android.media.action.IMAGE_CAPTURE intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);//置顶图片的输出地址 startActivityForResult(intent,RAKE_PHOTO); } }); } @Override protected void onActivityResult(int requestCode,int resultCode, Intent data){ //用startActivityForResult()启动活动会有结果返回到此方法中 switch (requestCode){ case TAKE_PHOTO: if(resultCode == RESULT_OK){ try{ //将拍摄的照片显示出来 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream((imageUri)); picture.setImageBitmap(bitmap); }catch (FileNotFoundException e){ e.printStackTrace(); } } break; default: break; } } }
在AndroidMainfest.xml中对内容提供器(FileProvider)进行注册:
- <provider
- android:authorities="com.example.cameraalbumtest.fileprovider" //必须和干菜FileProvider.getUriForFile()方法中第二个参数一致
- android:name="android.support.v4.content.FileProvider" //此属性值是固定的
- android:exported="false"
- android:grantUriPermissions="true">
- <meta-data //用<meta-data>来指定Uri的共享路径,并引用了一个@xml/file_path资源(下面我们来创建)
- android:name="android.support.FILE_PROVIDER_PATHS"
- android:resource="@xml/file_paths"/>
- </provider>
创建上面说的@xml/file_path资源
- <?xml version="1.0" encoding="utf-8" ?>
- <paths xmlns:andriod="http://schemas.android.com/apk/res/android">
- <enternal-path name="my_images" path=""/> //用来指定Uri共享,name属性值可以随便填,path属性的指标是共享的具体路径,此处为空表示共
- </paths> //享整个SD卡
在Android4.4之前,需要声明权限:
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.cameraalbumtest">
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在上面的基础上在布局文件中添加:
- <Button
- android:id="@+id/choose_from_album"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text=""Choose From Album/>
然后修改MainActivity文件中代码,加入从相册选择照片的逻辑:(红色为新增)
public class MainActivity extends AppCompatActivity { public static final int TAKE_PHOTO = 1; private ImageView picture; private Uri imageUri; public static final int CHOOSE_PHOTO = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button takePhoto = (Button) findViewById(R.id.take_photo); Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album); picture = (ImageView) findViewById(R.id.picture); takePhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); try { if (outputImage.exists()) { outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= 24) { imageUri = FileProvider.getUriForFile(MainActivity.this, "com/example.cameraalbumtest.fileprovider", outputImage); } else { imageUri = Uri.fromFile(outputImage); } Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, RAKE_PHOTO); } }); chooseFromAlbum.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(); } } }); } private void openAlbum() { Intent intent = new Intent("android.intent.action.GET_CONTENT");//将他的action指定为“”中的 intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO); //打开相册。第二个参数值为CHOOSE_PHOTO, } //当从相册选择完图片回到onActivityResult方法时,就会进入CHOOSE_PHOTO的case来处理图片 @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, 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: } } @Override protected void onActivityResult(int requestCode,int resultCode, Intent data){ switch (requestCode){ case TAKE_PHOTO: if(resultCode == RESULT_OK){ try{ //将拍摄的照片显示出来 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); picture.setImageBitmap(bitmap); }catch (FileNotFoundException e){ e.printStackTrace(); } } break; case CHOOSE_PHOTO: if(resultCode == RESULT_OK) { if (Build.VERSION.SDK_INT >= 19) { //进行版本判断 handleImageOnKitKat(data); } else { handleImageBeforeKitKat(data); } } break; default: break; } } @Target(19) private void handleImageOnKitKat(Intent data) { //如何解析这个封装过的Uri String imagePath = null; Uri uri = data.getData(); if( DocumentsContract.isDocumentUri(this,Uri)){ 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.Inages.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())){ imagePath = getImagePath(uri,null); }else if ("file".equalsIgnoreCase(uri.getScheme())){ imagePath = uri.getPath(); } displayImage(imagePath); } private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(rui,null); displayImage(imagePath); } private String getImagePath(Uri uri,String selection){ String path = null; 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); picture.setImageBitmap(bitmap); }else{ Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show(); } } }
应该有错,不过可以根据报错修改
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。