如何为用户提供从设备中的Camera / Gallery / DropBox或任何其他文件系统中选择图像并在活动中将其显示为ImageView对象的选项。

最佳答案

要从Camera / Gallery / DropBox或设备中的任何其他文件系统中选择图像,只需调用隐式意图即可。

以下代码可以帮助您...

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);
}
}

关于android - 从图库/相机/DropBox等中选取图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18870169/

10-09 12:59