android 系统4.4调用本地图库和系统相机

设置拍照和访问外置存储的权限




    
    
    
    

    
        
            
                

                
            
        
    

判断存储的Util类

public class FileUtils {
	//图片所在路径
    private static String filePath="";
	//返回图片觉得路径
    public static String getPath(String fileName){
        if(!isStorage()){
            return "";
        }
        filePath=Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+fileName;
        File file=new File(filePath);
        if(!file.exists()){
            file.mkdir();
        }
        return filePath;
    }
	//判断外置内存状态
    public static boolean isStorage(){
        return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }
}

MainActivity完整代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_photo,btn_local;
    private ImageView image_look;
    //图片名字
    private String fileName="";
    //图片所在文件夹名
    private String fileName2="Test";
    private int CALLCAMARE=1;
    private int LOCALIMAGE=2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findView();
    }

    private void findView() {
        btn_local= (Button) findViewById(R.id.btn_local);
        btn_photo= (Button) findViewById(R.id.btn_photo);
        image_look= (ImageView) findViewById(R.id.imag_look);
        btn_photo.setOnClickListener(this);
        btn_local.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
       if(v.getId()==btn_photo.getId()){
           fileName=FileUtils.getPath(fileName2);
           if(fileName.length()==0){
               Toast.makeText(this,"外置内存不存在,不能拍照",Toast.LENGTH_SHORT).show();
           }else{
               Intent intent = new Intent();
               intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
               intent.addCategory(Intent.CATEGORY_DEFAULT);
               startActivityForResult(intent, CALLCAMARE);
           }
       }
       if(v.getId()==btn_local.getId()){
           Intent intent = new Intent();
           intent.setType("image/*");// 从所有图片中进行选择
            //根据版本号不同使用不同的Action
           if (Build.VERSION.SDK_INT <19) {
               intent.setAction(Intent.ACTION_GET_CONTENT);
           }else {
               intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
           }
           startActivityForResult(intent,LOCALIMAGE);
       }

    }
    public String getFileNmae(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd_hhmmss");
        return sdf.format(new Date());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==CALLCAMARE&&resultCode==RESULT_OK){
            if(data!=null){
                showImage(data);
            }
        }
        if(requestCode==LOCALIMAGE&&resultCode==RESULT_OK){
            if (null!=data) {
                Uri uri = data.getData();
                InputStream inputStream = null;
                try {
		   //在网上找的简单获取4.4以上和4.4以下版本uri
                    inputStream = getContentResolver().openInputStream(uri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                image_look.setImageBitmap(bitmap);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showImage(Intent data) {
        {
            FileOutputStream fo=null;
            try{
                Bundle bund=data.getExtras();
                Bitmap bmp= (Bitmap) bund.get("data");
                fileName=fileName+File.separator+getFileNmae()+".jpg";
                File file=new File(fileName);
                fo=new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.JPEG,70,fo);
                image_look.setImageBitmap(bmp);
            }catch (Exception e){
                Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
            }finally {
                try{
                    fo.flush();
                    fo.close();
                }catch (Exception e){
                }
            }
        }
    }
}

4.4及以上版本根据uri获取图片路径

public static String getPath(final Context context, final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= 19;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}

				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {

			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		} else {

		}

		return null;
	}
       public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}


	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}


	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}


	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}

4.4以下根据uri获取图片路径

public static String getDataColumn(Context context, Uri uri,
			String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}



你可能感兴趣的:(Android)