在 Android 中使用 Intent 在活动中传递 android 位图数据 [英] Passing android Bitmap Data within activity using Intent in Android

查看:50
本文介绍了在 Android 中使用 Intent 在活动中传递 android 位图数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Activity1 中有一个名为 bmp 的位图变量,我想将位图发送到 Activity2

I hava a Bitmap variable named bmp in Activity1 , and I want to send the bitmap to Activity2

以下是我用来传递意图的代码.

Following is the code I use to pass it with the intent.

Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",bmp);
startActivity(in1);

在 Activity2 中,我尝试使用以下代码访问位图

And in Activity2 I try to access the bitmap using the following code

Bundle ex = getIntent().getExtras();
Bitmap bmp2 = ex.getParceable("image");
ImageView result = (ImageView)findViewById(R.Id.imageView1);
result.setImageBitmap(bmp);

应用程序运行无异常,但没有给出预期的结果

The application runs without an exception but it does not give the expected result

推荐答案

在将其添加到 Intent、发送出去和解码之前,将其转换为 Byte 数组.

Convert it to a Byte array before you add it to the intent, send it out, and decode.

//Convert to byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",byteArray);

然后在活动 2 中:

byte[] byteArray = getIntent().getByteArrayExtra("image");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

<小时>

编辑

我想我应该用最佳实践更新这个:

Thought I should update this with best practice:

在您的第一个活动中,您应该将位图保存到磁盘,然后在下一个活动中加载它.确保在第一个活动中回收您的位图以准备好进行垃圾收集:

In your first activity, you should save the Bitmap to disk then load it up in the next activity. Make sure to recycle your bitmap in the first activity to prime it for garbage collection:

活动 1:

try {
    //Write file
    String filename = "bitmap.png";
    FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

    //Cleanup
    stream.close();
    bmp.recycle();

    //Pop intent
    Intent in1 = new Intent(this, Activity2.class);
    in1.putExtra("image", filename);
    startActivity(in1);
} catch (Exception e) {
    e.printStackTrace();
}

在活动 2 中,加载位图:

In Activity 2, load up the bitmap:

Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
    FileInputStream is = this.openFileInput(filename);
    bmp = BitmapFactory.decodeStream(is);
    is.close();
} catch (Exception e) {
    e.printStackTrace();
}

干杯!

这篇关于在 Android 中使用 Intent 在活动中传递 android 位图数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆