Efficiently putting image Filters in Android

1 min read

Android Development

Dear Readers

Few months back we were planning to put image filters to one of our demo image filters app for android. So we started doing some initial research and we came to know about one of the best available library for processing imagefilters. Link

Its an open source lib which helped us to achieve out goal. Then few days later we had some different requirements. So we tried to tackle the requirements using this lib but I think we integrated the lib wrongly so might be that could be the reason why our code was not performing efficiently (fast) when there are large no of filter operation to be performed. As always if you honestly work hard and learn, so even if you don’t get expected results , you are not in loss conceptually,  you left with hard work .

So we were left with our hard work and learning we had. Then we came to know about ColorMatrix in Android and which can be used to put image filters efficiently in android.


Lets dive into code


private void applyBlueFilter(Bitmap baseBitmap, ImageView imageView) {
    Bitmap afterBitmap = Bitmap.createBitmap(baseBitmap.getWidth(),
            baseBitmap.getHeight(), baseBitmap.getConfig());
    Canvas canvas = new Canvas(afterBitmap);
    Paint paint = new Paint();

    BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getImageView().getDrawable();
    Bitmap bmp = bitmapDrawable.getBitmap();

    float lr = 75;
    float lg = 255;
    float lb = 245;
    float la = 22f;
    Log.i(TAG, "R: G: B=" + lr + ": " + lg + ": " + lb);
    // According to the definition of the RGBA matrix SeekBar
    float[] src = new float[]{
            lr / 255, 0, 0, 0, 0, //
            0, lg / 255, 0, 0, 0, //
            0, 0, lb / 255, 0, 0, //
            0, 0, 0, 1, la   //

    // The definition of ColorMatrix, and specify the RGBA matrix
    ColorMatrix colorMatrix = new ColorMatrix();
    // Set the Paint color
    paint.setColorFilter(new ColorMatrixColorFilter(src));
    // By specifying the RGBA matrix Paint of the original picture of the blank picture
    canvas.drawBitmap(baseBitmap, new Matrix(), paint);


So we provide a float[] array to initialize colomatrix. and then we can use it to put image filter.

As per dev docs 

4×5 matrix for transforming the color and alpha components of a Bitmap. The matrix can be passed as single array, and is treated as follows:


  [ a, b, c, d, e,
    f, g, h, i, j,
    k, l, m, n, o,
    p, q, r, s, t ]

When applied to a color [R, G, B, A], the resulting color is computed as:

   R = a*R + b*G + c*B + d*A + e;
   G = f*R + g*G + h*B + i*A + j;
   B = k*R + l*G + m*B + n*A + o;
   A = p*R + q*G + r*B + s*A + t;


That resulting color [R’, G’, B’, A’] then has each channel clamped to the 0 to 255 range.

So you can play with changing values in float [] array and then a different color filter can be used.

And doing that will be very efficient.