Search code examples
androidkotlinpicassoandroid-bitmap

Can't get Bitmap from ImageView as a BitmapDrawable


In my Android - Kotlin application , I'm trying to get the bitmap out of an image to use it's colorPallete, here is the ImageView in my XML file:

        <ImageView
            android:id="@+id/dressImage_1"
            android:layout_width="142dp"
            android:layout_height="123dp"
            android:contentDescription="@string/app_name"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/icon" />

and here is how i add an Image to it :

Picasso.get().load(dress.image1).into(mDressImage1)

all goes fine to here.

Note:dress.image1 returns an URL

After this, when I try to get the bitmap from the imageView this way :

        val bitmap = (mDressImage1?.drawable as BitmapDrawable).bitmap

it simply crashes. with nothing at the logcat

UPDATE it gave me the error null cannot be cast to non-null type android.graphics.drawable.BitmapDrawable

pointing at the line val bitmap = (mDressImage1?.drawable as BitmapDrawable).bitmap


Solution

  • This should solve your problem:

    val bitmap = (mDressImage1?.drawable as? BitmapDrawable)?.bitmap