import java.awt.image.*;
import java.awt.*;

// This demonstrates the process of creating your own
// "homemade" color filter from Java's existing
// RGBImage class.

// In this case, we define a new "ShadowFilter" class,
// which edits the colors of pixels based on their
// distance from the left of the image, adding more
// shadow to the left of the image.

// Your filter must extend the existing RGBImageFilter
// class (which will do most of the work of getting
// and manipulating pixels).

public class ShadowFilter extends RGBImageFilter {

  // Since we will add shading in proportion to how far
  // the left a pixel is, we need to know the total
  // width of the image (which will be passed to the
  // contructor).

  private int width;

  public ShadowFilter(int w) {
    width = w;
    }

  // The filterRGB method is the key method to define.
  // It takes the x, y coordinates of the pixel and
  // the current color of the pixel (as a single number
  // in hex). You must define and return the new color
  // value of that pixel. This method will be repeatedly
  // called by the ImageProducer and applied to every
  // pixel in the image it is applied to.

  public int filterRGB(int x, int y, int rgb) {

    // It will be simpler to work with the red, green,
    // and blue values of the pixel than the single hex
    // number. The simplest way to get these is to create
    // a Color object from the hex number, and then apply
    // the getRed, getGreen, and getBlue methods to that Color.

    Color oldColor = new Color(rgb);
    int oldRed = oldColor.getRed();
    int oldGreen = oldColor.getGreen();
    int oldBlue = oldColor.getBlue();

    // We now compute the new red, green, and blue values to
    // display at this pixel. This is the critial part of the code!

    // Here, we add shadow in proportion to how close the pixel
    // is to the left edge by multiplying the pixel brightness
    // by that distance (scaled by the total width of the image).

    int newRed = (int)(oldRed * x / width);
    int newGreen = (int)(oldGreen * x / width);
    int newBlue = (int)(oldBlue * x / width);

    // Since we must return a single hex RGB value, the simplest
    // way to create one is to create a new COlor from the new red,
    // green, and blue values, and then use the getRGB method to
    // return the result.

    Color newColor = new Color(newRed, newGreen, newBlue);
    return newColor.getRGB();
    }

  }

