0

I have searched online for a tutorial on how to send a bitmap data over to another activity using the putExtra() method in kotlin, but nothing seems to pop up. I do not know how to code in java so all the tutorials and stack overflow threads that talk about converting to a byte array do not help much. Can someone please help me with maybe a solution?

What I did so far (My project is in no regards to this post) is I saved a image using my camera as a bitmap using the code:

val thumbnail : Bitmap = data!!.extras!!.get("data") as Bitmap

(the key word "data" is a intent inside the upper override function (onActivityResult)) This saves a bitmap of the image I took with the camera and now I tried to send it over, using the putExtra() command as so:

var screenSwitch2 = Intent(this@MainActivity,mlscreen::class.java)
screenSwitch2.putExtra("bitmap", thumbnail)

On the other screen "mlscreen" I tried to recover the data using a intent.getStringExtra("bitmap")

val thumbnail = intent.getStringExtra("bitmap")

and then I set my image view in the "mlscreen" using the setImageBitmap method as here:

iv_image.setImageBitmap(thumbnail)

I got the error that I was looking for a bitmap data and not a string data for the method. I knew this would occur though because I had to use intent.getSTRINGExtra which would mean its converting it to a string I presume.

Any help with this would be appreciated! Thanks.

  • https://stackoverflow.com/questions/26939759/android-getintent-from-a-fragment – umar ali Khan Jan 02 '23 at 20:55
  • "I have searched online for a tutorial on how to send a bitmap data over to another activity using the putExtra() method" -- that is because it is generally not a good idea. It will only work for small images. You might consider using a single activity instead of two, with fragments (or composables) implementing the different screens. Alternatively, *carefully* have your image be managed by a singleton repository, and have each activity interact with that repository. – CommonsWare Jan 02 '23 at 20:56

1 Answers1

0

There are 3 ways to do that :

1 - Using Intent (not recommended)

ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
intent.putExtra("image", b);
startActivity(intent);

2 - Using static (not recommended)

public static Bitmap thumbnail;

3 - Using Path (recommended)

  • Save your Bitmap as an image file in specific folder (make it invisible to the users).
  • Get the path from the saved file.
  • Use intent.putExtrat("imagePath",path);.
  • Use BitmapFactory.decodeFile(filePath); to get the Bitmap from the path.
  • Remove the path.