pass a bitmap image from one activity to another

后端 未结 8 1613
清酒与你
清酒与你 2020-12-05 21:57

In my app i am displaying no.of images from gallery from where as soon as I select one image , the image should be sent to the new activity where the selected image will be

8条回答
  •  醉话见心
    2020-12-05 22:31

    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");
    

    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);
    

提交回复
热议问题