【问题标题】:Select a photo from gallery in Android App在 Android 应用中从图库中选择一张照片
【发布时间】:2020-10-30 19:18:09
【问题描述】:

我希望能够从图库中选择图像并能够显示它并放大/缩小 我试过这段代码只是为了选择一张图片

public static final int PICK_IMAGE = 1;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button buttonLoadImage = (Button) findViewById(R.id.button);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                 Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 startActivityForResult(i, PICK_IMAGE);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
    }

当我尝试查看它是否有效时..它打开了画廊但是当我在图像中选择时..它没有出现在图像视图中 我该如何解决它以及如何能够放大和缩小

【问题讨论】:

    标签: android imageview


    【解决方案1】:

    在 onActivityResult() 中使用这段代码

        if (resultCode == RESULT_OK) {
                try {
                    final Uri imageUri = data.getData();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap bitmapImage= BitmapFactory.decodeStream(imageStream);
                    ImageView imageView = (ImageView) findViewById(R.id.imageView);
                    imageView.setImageBitmap(bitmapImage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
                }
    
            }else {
                Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
            }
        }
    

    【讨论】:

    【解决方案2】:

    在 onActivityResult 中:

      imageView.setImageUri(data.getData());
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2020-10-02
      • 2016-07-13
      • 1970-01-01
      相关资源
      最近更新 更多