使用android意图在活动中传递android位图数据

使用android意图在活动中传递android位图数据

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

下面是我用来传递它的意图的代码。

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

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

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

应用程序毫无例外地运行,但它没有给出预期的结果。


幕布斯6054654
浏览 424回答 3
3回答

慕容森

在将其添加到意图之前,将其转换为Byte数组,然后将其发送出去并解码。//Convert to byte arrayByteArrayOutputStream 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);编辑我想我应该用最佳实践来更新它:在第一个活动中,应该将位图保存到磁盘,然后在下一个活动中加载它。确保在第一个活动中循环使用位图,使其成为垃圾收集的主要内容:活动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();}干杯!

冉冉说

有时,位图可能太大,无法编码和解码,也不能作为字节数组传递。这可能会导致OOM或糟糕的UI体验。我建议考虑将位图放入新活动的静态变量(使用它的那个),当您不再需要它时,它将谨慎地为空(在onDesty中,但只有当“isChangingConfigurations”返回false时,它的含义才是空的)。

精慕HU

简单地说,我们可以只传递Bitmap的URI,而不是传递Bitmap对象。如果位图对象很大,这将导致内存问题。第一行动。intent.putExtra("uri", Uri);从第二个活动中我们得到位图。Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),Uri.parse(uri));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android