Usman Ali
Usman Ali

Reputation: 433

Change Bitmap Background Color

I am Working on Android App which has to change Image Color by Using this library https://github.com/divyanshub024/ColorSeekBar, the Issue I am facing is as I Set image background Color, It only changes Borders. I have An Imageview that is been Converted from byte array to bitmap and Set into ImageView.

 <ImageView
    android:id="@+id/img_bitmap1"
    android:layout_width="match_parent"
    android:layout_height="@dimen/_300sdp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="@dimen/_10sdp"
    android:layout_marginStart="@dimen/_10sdp"
    android:layout_marginEnd="@dimen/_10sdp"
    />

How I am Converting Byte array to Bitmap and Setting into ImageView

val byteArray = intent.getByteArrayExtra("pictures")
    val bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    img_bitmap1.setImageBitmap(bmp)

How I am Changing Color

 val imageview = requireActivity()!!.findViewById<View>(R.id.img_bitmap1) as ImageView

    color_seek_bar.setOnColorChangeListener(object : ColorSeekBar.OnColorChangeListener {
        override fun onColorChangeListener(color: Int) {
            imageview.setBackgroundColor(color)
        }
    })

Upvotes: 0

Views: 1347

Answers (2)

Usman Ali
Usman Ali

Reputation: 433

The Problem get Resolved by changing Imageview Color by Getting the Pixel Value, and Only Changing the Pixels that's color is rather than the white.. this Get Achieved by this Method.

 var bitmap = (imageviewgradient.drawable as BitmapDrawable).bitmap
            var newBitmap = replaceColor(bitmap, color)

The Above Code is Converting Image to Bitmap

    private fun replaceColor(src: Bitmap?, targetColor: Int): Bitmap? {
    if (src == null) {
        return null
    }
    // Source image size
    val width = src.width
    val height = src.height
    val pixels = IntArray(width * height)
    //get pixels
    src.getPixels(pixels, 0, width, 0, 0, width, height)
    for (x in pixels.indices) {
        if(pixels[x]!=-1) {
            pixels[x] = targetColor
        }
    }
    // create result bitmap output
    val result = Bitmap.createBitmap(width, height, src.config)
    //set pixels
    result.setPixels(pixels, 0, width, 0, 0, width, height)
    return result
}

The Main Working is Just Done by a Simple Condition i.e

if(pixels[x]!=-1) {
            pixels[x] = targetColor
        }

Upvotes: 0

snachmsm
snachmsm

Reputation: 19253

the question is what is showing your ImageView, what contains val bmp set for it. your seek bar is changing background properly and you see only borders changed, because "center" of image (almost whole) is covered by some bitmap

try to NOT load val bmp into ImageView and check if whole background is changing, not only frame

Upvotes: 1

Related Questions