Passing android Bitmap Data within activity using Intent in Android

前端 未结 7 1579
梦如初夏
梦如初夏 2020-11-22 09:36

I hava a Bitmap variable named bmp in Activity1 , and I want to send the bitmap to Activity2

Following is the code I use to pass it with the intent.

7条回答
  •  孤城傲影
    2020-11-22 09:42

    Kotlin Code for send Bitmap to another activity by intent:

    1- in First Activity :

              val i = Intent(this@Act1, Act2::class.java)
               var bStream  =  ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, bStream)
                val byteArray = bStream.toByteArray()
                i.putExtra("image", byteArray )
                startActivity(i)
    

    2- In Activity two (Read the bitmap image) :

     var bitmap : Bitmap? =null
        if (intent.hasExtra("image")){
          //convert to bitmap          
            val byteArray = intent.getByteArrayExtra("image")
            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
        }
    

    3- if you need to set it as background for a view, like ConstraintLayout or... :

     if (bitmap != null) {
         //Convert bitmap to BitmapDrawable
         var bitmapDrawable = BitmapDrawable( resources , bitmap)
          root_constraintLayout.backgroundDrawable = bitmapDrawable
       }
    

提交回复
热议问题