如何将位图图像转移到另一个活动中?

时间:2019-03-03 02:39:27

标签: java android parsing bitmap uri

为什么我的代码不起作用?我想将图像从一项活动转移到另一项活动。请帮忙!注意:我已经创建了一个摄像头功能,这就是我获取图像的地方。

这是MainActivity.java

public class MainActivity extends AppCompatActivity {

public static final int CAMERA_REQUEST = 9999;

ImageView imageView1;
Button camera,send;

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

    imageView1 = findViewById(R.id.imageView1);
    camera = findViewById(R.id.camera);
    send = findViewById(R.id.send);

    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent d1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(d1, CAMERA_REQUEST);
        }
    });

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            imageView1.buildDrawingCache();
            Bitmap bitmap = imageView1.getDrawingCache();

            Intent intent = new Intent(MainActivity.this, ResultActivity.class);  
            intent.putExtra("bp", bitmap);

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Bitmap bitmap = (Bitmap) data.getExtras().get("data");
    imageView1.setImageBitmap(bitmap);
}
}

这是ResultActivity.java

public class ResultActivity extends AppCompatActivity {

ImageView imageView2;

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

    imageView2 = findViewById(R.id.imageView2);

    Intent intent = new Intent();
    Bitmap bitmap = intent.getParcelableExtra("bp");
    imageView2.setImageBitmap(bitmap);
    }
}  

如果我做错了什么。请告诉我。谢谢

1 个答案:

答案 0 :(得分:0)

您已经按照“ OnActivityResult”中接收的意图将位图作为Uri接收。 您所要做的就是使用此意图进行第二个活动。 然后从那里可以将其转换为位图:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Intent intent = new Intent(MainActivity.this, ResultActivity.class);  
    intent.putExtra("Some key",data.getData().toString());
    Bitmap bitmap = (Bitmap) data.getExtras().get("data");
    imageView1.setImageBitmap(bitmap);
}
}

关于ResultActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    Uri uri = Uri.parse(getIntent.getExtra.getString("Some key"));
    imageView2 = findViewById(R.id.imageView2);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

    imageView2.setImageBitmap(bitmap);
    }
}