how do you pass images (bitmaps) between android activities using bundles?

后端 未结 9 1193
自闭症患者
自闭症患者 2020-11-22 09:56

Suppose I have an activity to select an image from the gallery, and retrieve it as a BitMap, just like the example: here

Now, I want to pass this BitMap to be used i

9条回答
  •  遥遥无期
    2020-11-22 10:40

    Activity

    To pass a bitmap between Activites

    Intent intent = new Intent(this, Activity.class);
    intent.putExtra("bitmap", bitmap);
    

    And in the Activity class

    Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
    

    Fragment

    To pass a bitmap between Fragments

    SecondFragment fragment = new SecondFragment();
    Bundle bundle = new Bundle();
    bundle.putParcelable("bitmap", bitmap);
    fragment.setArguments(bundle);
    

    To receive inside the SecondFragment

    Bitmap bitmap = getArguments().getParcelable("bitmap");
    

    Transferring large bitmap (Compress bitmap)

    If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.

    So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this

    In the FirstActivity

    Intent intent = new Intent(this, SecondActivity.class);
    
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
    byte[] bytes = stream.toByteArray(); 
    intent.putExtra("bitmapbytes",bytes);
    

    And in the SecondActivity

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

提交回复
热议问题