Use BufferedImage for gradient operation

  java

Order

This article mainly describes how to use BufferedImage for gradient operation.

GradientPaint

java/awt/GradientPaint.java

public class GradientPaint implements Paint {
    Point2D.Float p1;
    Point2D.Float p2;
    Color color1;
    Color color2;
    boolean cyclic;
   //......   
}    

This is the key class to generate gradient, of course there are other gradient classes, such as
java/awt/LinearGradientPaint.java

Example

public static BufferedImage drawGradient(BufferedImage srcImg,
                                             int startX, int startY,
                                             int endX, int endY,
                                             Color colorFrom, Color colorTo,
                                             float opacity) {
        BufferedImage dstImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB);
        GradientPaint grad = new GradientPaint(startX, startY, colorFrom, endX, endY, colorTo); //从左上到右下渐变;

        Graphics2D g2 = (Graphics2D) dstImg.getGraphics();
        g2.setPaint(grad);
        g2.fillRect(startX, startY, endX, endY);

        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, opacity));
        g2.drawImage(srcImg, 0, 0, srcImg.getWidth(), srcImg.getHeight(), null);
        g2.dispose();

        return dstImg;
    }

The principle is to use GradientPaint to draw a rectangle with gradually changing color, and then cover the original image with a certain transparency to see the gradual change.
If it is not enough, the gradient color will be lighter.