GrayScale FIlter

Excellence is not enough!

GrayScale FIlter

In This Post I’ll Show You How To Filter Image Like An Old Black And White Shot.

To

  

There Is A Simple Explanation To The Concept , Each Pixel In A Bitmap Image Has Three Color Values That Explains The Overall Color Of That Pixel (For Example Red : 211, Green : 47, Blue : 47 Shows Material Red 700 Color) , But If A Pixel Has Similar Color Values (For Example 120 , 120 , 120) This Indicates That Pixel Has A Gray Color Ranging From Lite To Dark , So If We Could Convert Each Pixel Color Values To A Equal Number We Have An Image That Beautiful Sharp Colors Has Disappeared And Gloomy Grays Have Covered Everything.

So How We Accomplish This ? Simply By Getting Average Of Pixel Color Values , Just That : (Red + Blue + Green) / 3 .

So Let’s Start Coding:

public static Bitmap applyGrayScale(Bitmap src ){
     int width = src.getWidth() ;
     int height = src.getHeight() ;
     Bitmap out = Bitmap.createBitmap(width , height , src.getConfig()) ;
     int[] pixels = new int[width * height] ;
     src.getPixels(pixels , 0 , width
      , 0 ,0 , width , height);
     int a , r , g , b ;
     int index = 0  ;
     int average = 0 ;
     for (int y = 0 ; y < height ; y++)
         for (int x = 0 ;x < width ; x++){
         {
             index = y * width + x ;
             a = Color.alpha(pixels[index]) ;
             r = Color.red(pixels[index]) ;
             g = Color.green(pixels[index]) ;
             b = Color.blue(pixels[index]) ;
             average = ( r + g +b) / 3 ;
             pixels[index] = Color.argb(a , average , average , average) ;
         }
     }
     out.setPixels(pixels , 0 , width , 0 , 0 , width , height);
     return out ;
 }

 

First Off We Collect Pixels Into An Array To Use Later :

src.getPixels(pixels , 0 , width , 0 ,0 , width , height);

 

Then We Traverse Through Pixels To Be Able To Get Color Numbers :

a = Color.alpha(pixels[index]) ;

r = Color.red(pixels[index]) ;

g = Color.green(pixels[index]) ;

b = Color.blue(pixels[index]) ;

 

Now We Have Color Numbers , We Just Need To Get The Averege :

average = ( r + g +b) / 3 ;

 

And At The End Set The Color Numbers :

pixels[index] = Color.argb(a , average , average , average) ;

 

Thats It , Now We Have A Gray Scale Image In Such A Simple Way !.