java如何填充图片
使用Graphics2D绘制填充图片
在Java中,可以通过Graphics2D类实现图片填充操作。创建一个指定大小的BufferedImage,获取其Graphics2D对象后,使用fillRect或fill方法填充颜色或形状。
import java.awt.*;
import java.awt.image.BufferedImage;
public class ImageFiller {
public static BufferedImage createFilledImage(int width, int height, Color color) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(color);
g2d.fillRect(0, 0, width, height);
g2d.dispose();
return image;
}
}
使用渐变填充
GradientPaint类可实现线性渐变填充效果。通过定义起始点、结束点及对应的颜色,创建渐变对象后传递给Graphics2D。
public static BufferedImage createGradientImage(int width, int height, Color startColor, Color endColor) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
GradientPaint gradient = new GradientPaint(0, 0, startColor, width, height, endColor);
g2d.setPaint(gradient);
g2d.fillRect(0, 0, width, height);
g2d.dispose();
return image;
}
纹理填充图片
通过TexturePaint类可使用另一张图片作为纹理进行填充。需将纹理图片转换为BufferedImage并定义填充区域。
public static BufferedImage createTextureImage(int width, int height, BufferedImage texture) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
TexturePaint texturePaint = new TexturePaint(texture, new Rectangle(0, 0, texture.getWidth(), texture.getHeight()));
g2d.setPaint(texturePaint);
g2d.fillRect(0, 0, width, height);
g2d.dispose();
return image;
}
填充现有图片部分区域
对已有图片的特定区域进行填充时,需先加载原图,再通过Graphics2D操作目标区域。
public static void fillImageRegion(BufferedImage image, int x, int y, int width, int height, Color color) {
Graphics2D g2d = image.createGraphics();
g2d.setColor(color);
g2d.fillRect(x, y, width, height);
g2d.dispose();
}
使用AlphaComposite实现半透明填充
通过设置AlphaComposite实例,可实现带透明度的填充效果。适用于需要叠加颜色的场景。

public static void fillWithTransparency(BufferedImage image, Color color, float alpha) {
Graphics2D g2d = image.createGraphics();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2d.setColor(color);
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
g2d.dispose();
}






