flutterdartimage-processingcolormatrix

How to adjust Hue Saturation and Brightness of an image or widget in Flutter?


In my Flutter app, I have an image and three sliders, one for Hue, one for Saturation, and one for Brightness, and I'm trying to figure out how to use the ColorFiltered widget to make these adjustments, but I can't figure out what to put in for the ColorFilter.matrix.

My code looks something like this:

ColorFiltered(
  colorFilter: ColorFilter.matrix(
    // What goes here?
  ),
  child: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        fit: BoxFit.cover,
        image: NetworkImage(myImageUrl),
      )
    )
  )
)

Does anyone know how to generate a color filter matrix based on HSV values?


Solution

  • I've added BananaNeil's answer into the Themed package.

    Use the provided ChangeColors widget to change the brightness, saturation and hue of any widget, including images, like this:

    ChangeColors(
       hue: 0.55,
       brightness: 0.2,
       saturation: 0.1,
       child: Image.asset('myImage.png'),
    );
    

    Parameters are:

    brightness

    • Negative value will make it darker (-1 is darkest).
    • Positive value will make it lighter (1 is the maximum, but you can go above it).
    • 0.0 is unchanged.

    saturation

    • Negative value will make it less saturated (-1 is greyscale).
    • Positive value will make it more saturated (1 is the maximum, but you can go above it).
    • 0.0 is unchanged.

    hue

    • From -1.0 to 1.0 (Note: 1.0 wraps into -1.0, such as 1.2 is the same as -0.8).
    • 0.0 is unchanged. Adding or subtracting multiples of 2.0 also keeps it unchanged.

    Please note: The difference from the ChangeColors widget to BananaNeil's answer is that the widget is a proper StatelessWidget, code is null-safe, it fixes the limits of saturation so that you don't get weird effects, and the documentation was added explaining the parameters. If you don't want to add a package, just copy the code from GitHub.