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

查看:117
本文介绍了在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

推荐答案

在将其添加到意图中,将其发送出去并进行解码之前,请将其转换为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天全站免登陆