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

时间:2019-03-20 08:04:30

标签: android android-bitmap

我使用受保护的void onActivityResult 从图库中获取位图图像。  现在,我想获取此位图图像的信息,以在同一活动中将其用于其他方法。  这是我的代码: 我使用受保护的void onActivityResult从图库中获取位图图像。现在,我想获取此位图图像的信息,以在同一活动中将其用于其他方法。这是我的代码:

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

将位图设置为图像后,您可以通过不同的方法将位图附加到同一ImageView上:

Bitmap bitmap = ((BitmapDrawable)imagev.getDrawable()).getBitmap();