Android:从任何来源获取图片

时间:2015-06-28 08:26:11

标签: android android-intent camera gallery handle

我正在尝试从任何来源(如Dropbox,gallery,camera,retrica等)获取图像,获取他的路径并将其设置在ImageView上。通过使用此意图

  private void cameraIntent() {
      Intent pickIntent = new Intent();
        pickIntent.setType("image/*");
        pickIntent.setAction(Intent.ACTION_GET_CONTENT);

        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


        String pickTitle = "Select or take a new Picture";
        Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
        chooserIntent.putExtra
                (
                        Intent.EXTRA_INITIAL_INTENTS,
                        new Intent[]{takePhotoIntent}
                );

        startActivityForResult(chooserIntent, REQUEST_CAMERA);

    }

但现在,我只能处理图库和相机意图,我该如何处理其他应用?

1 个答案:

答案 0 :(得分:0)

从Camera / Gallery / DropBox中挑选图像或从设备中选择任何其他文件系统只需调用隐式intent ...

以下代码可以帮助您..

pickbtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v){
            if (Environment.getExternalStorageState().equals("mounted")){
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Picture:"), Constants.PICK_IMAGE_FROM_LIBRARY);
            }
        }
    });

现在使用OnActivity结果获取数据......

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == Constants.PICK_IMAGE_FROM_LIBRARY)
    {
        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            String selectedImagePath = getPath(selectedImageUri);
            mImagePath = selectedImagePath;
            Bitmap photo = getPreview(selectedImagePath);
            mImageViewProfileImage.setImageBitmap(photo);
        }
    }
public String getPath(Uri uri)
{
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

public Bitmap getPreview(String fileName)
{
    File image = new File(fileName);

    BitmapFactory.Options bounds = new BitmapFactory.Options();
    bounds.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(image.getPath(), bounds);

    if ((bounds.outWidth == -1) || (bounds.outHeight == -1)) 
    {
        return null;
    }
    int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight : bounds.outWidth;
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = originalSize / 64;
    return BitmapFactory.decodeFile(image.getPath(), opts);
}
}

这是一个完整的例子:https://gist.github.com/felixgborrego/7943560