使用Android的意图派位图 [英] send Bitmap using intent Android

查看:111
本文介绍了使用Android的意图派位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我哈瓦在活动1名位图变量 BMP ,我想用这个code将其发送到活性2:

I hava a Bitmap variable in Activity1 name is bmp, and i want to send it to Activity2 using this code :

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

和中活性2我把它称为是这样的:

And in Activity2 i call it like this :

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

为什么当我运行它只是运行,并且没有给出任何结果的程序?任何人都可以帮我吗?

why when i run the program it just running and not give any result?? anyone can help me??

推荐答案

将其转换为一个字节数组,你把它添加到意图之前,将它发送出去,去code。

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:

Then in Activity 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,装载位图:

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的意图派位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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