如何从onActivityResult获取位图信息并在同一活动中使用它

问题描述 投票:0回答:3

我使用protected void onActivityResult从gallery获取位图图像。现在我想获取此位图图像的信息,以便在同一活动中的另一个方法中使用它。这是我的代码:我使用protected void onActivityResult从gallery获取位图图像。现在我想获取此位图图像的信息,以便在同一活动中的另一个方法中使用它。这是我的代码:

public class MainActivity extends AppCompatActivity {
private static final int selected_image = 1;
Bitmap bitmap;
ImageView imagev;
public static int n, m;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imagev = findViewById(R.id.imagev);
}


public void btnselectimage(View view) {
    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, selected_image);
    // I want get the width and height of this image here;
    System.out.println("width=" + n);
    System.out.println("height=" + m);
}


//  @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case selected_image:
            if (resultCode == RESULT_OK) {

                Uri uri = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

                bitmap = BitmapFactory.decodeFile(picturePath);
                n = bitmap.getWidth();
                m = bitmap.getHeight();
                //  Drawable d = new BitmapDrawable(bitmap);
                imagev.setImageBitmap(bitmap);
            }
            break;
    }
  }
}
android android-bitmap
3个回答
3
投票
    Bitmap bitmap;
    if (mImageViewer.getDrawable() instanceof BitmapDrawable) {
        bitmap = ((BitmapDrawable) mImageViewer.getDrawable()).getBitmap();
    } else {
       imageView.invalidate();
       BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
       bitmap = drawable.getBitmap();
    }

1
投票

将位图设置为图像后,您可以使用不同的方法将位图附加到相同的ImageView,如下所示:

Bitmap bitmap = ((BitmapDrawable)imagev.getDrawable()).getBitmap();
© www.soinside.com 2019 - 2024. All rights reserved.