Friday, September 9, 2011

GraphUtil - class for setting brightness and grayscale in Image

Recently in one of my projects I needed to change brightness in image that was in Spark Image control. It got me some time to find the best solution to do that. Finally I made my own class - GraphUtil. This class use ColorMatrixFilter to do all the magic. This is code for that class:

public class GraphUtil
{
  public function GraphUtil()
  {
  }
  
  public static function brightnessFilter(brightnessChange:Number):ColorMatrixFilter
  {
    var matrix:Array = new Array();
    matrix = matrix.concat([1, 0, 0, 0, brightnessChange]); // red
    matrix = matrix.concat([0, 1, 0, 0, brightnessChange]); // green
    matrix = matrix.concat([0, 0, 1, 0, brightnessChange]); // blue
    matrix = matrix.concat([0, 0, 0, 1, 0]);  // alpha
   
    return new ColorMatrixFilter(matrix);    
  }
  
  public static function grayscaleFilter():ColorMatrixFilter
  {
    var matrix:Array = new Array();
    matrix = matrix.concat([0.5, 0.5, 0.5, 0, 0]); // red
    matrix = matrix.concat([0.5, 0.5, 0.5, 0, 0]); // green
    matrix = matrix.concat([0.5, 0.5, 0.5, 0, 0]); // blue
    matrix = matrix.concat([0, 0, 0, 1, 0]);  // alpha
   
    return new ColorMatrixFilter(matrix);    
  }
}

Method brightnessFilter() allows you to change brightness on image. When you set brightnessChange variable to positive value the output filter will lighten your image. After setting this variable to negative value you can darken your image. Method grayscaleFilter() change your image colour scheme to grayscale.

OK so you probably ask how to use that Class? I will show you that in my next blog post, along with a quite interesting use case.

No comments:

Post a Comment