Search code examples
javaandroidbitmappixel

grayscale image displays red - android


I have some weird issue. I set a gray scale Bitmap from an int[] pixel array. So I put this

    bitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
    byte[] byteArray = new String(pixelsArray).getBytes("UTF-8");
    Bitmap bitmap = getBitmapFromByte(byteArray, pixelsArray.length);
    ImageView theImage = (ImageView) findViewById(R.id.echo);
    theImage.setImageBitmap(bitmap);

The problem is that I get the correct image but in red color. So I thought this was related to ImageView wrapper that holds the bitmap.

<LinearLayout
        android:id="@+id/some_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/theme_blue"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/echo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/some_image" />

So I put

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.vMiddle);
linearLayout.setBackgroundColor(Color.BLACK);

But it still displays in red. Someone has an idea ? Btw, I tested the int[] pixels array on a test plain java app, and it displays correctly with grayscale colors.


Solution

  • Use a ColorMatrix and ColorMatrixColorFilter to set the ImageView's contents to grayscale.

    ColorMatrix matrix = new ColorMatrix();
    matrix.setSaturation(0);
    
    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
    

    Then simply set the ImageView to utilize the filter.

    ImageView imageView = (ImageView)findViewById(R.id.imageView);
    imageView.setColorFilter(filter);
    

    This will make the contents of the ImageView be grayscale.