程序功能
图像初始化:创建一个800x800像素的 BufferedImage 对象,并使用 Graphics2D 来绘制图形。
颜色渐变背景:随机生成两个颜色,使用 GradientPaint 在图片的对角线方向上创建从一种颜色到另一种颜色的渐变效果,填充整个图片作为背景。
随机几何图形:在图片上随机绘制20个矩形或椭圆形,这些图形的颜色、位置、大小都是随机生成的。图形的颜色是半透明的(透明度为128),使得它们与背景渐变颜色相融合,增加了艺术感。
文件保存:生成的图片以PNG格式保存,并使用当前时间戳和随机数生成一个唯一的文件名。
代码
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.Random;
public class ArtisticImageGenerator {
public static void main(String[] args) {
int width = 800; // 图片宽度
int height = 800; // 图片高度
// 创建一个BufferedImage对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 使用Graphics2D绘图
Graphics2D graphics = image.createGraphics();
// 随机生成颜色渐变
Random random = new Random();
Color color1 = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
Color color2 = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
// 创建颜色渐变效果
GradientPaint gradient = new GradientPaint(0, 0, color1, width, height, color2);
graphics.setPaint(gradient);
graphics.fillRect(0, 0, width, height);
// 在图片上添加一些随机的几何图形
for (int i = 0; i < 20; i++) {
// 随机选择形状的颜色
Color shapeColor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256), 128); // 透明度为128
graphics.setColor(shapeColor);
// 随机选择形状的大小和位置
int shapeWidth = random.nextInt(200) + 50;
int shapeHeight = random.nextInt(200) + 50;
int x = random.nextInt(width - shapeWidth);
int y = random.nextInt(height - shapeHeight);
// 随机绘制矩形或椭圆形
if (random.nextBoolean()) {
graphics.fillRect(x, y, shapeWidth, shapeHeight);
} else {
graphics.fillOval(x, y, shapeWidth, shapeHeight);
}
}
// 释放图形资源
graphics.dispose();
// 生成随机文件名
String fileName = "artistic_image_" + System.currentTimeMillis() + "_" + random.nextInt(10000) + ".png";
// 将图片保存为PNG文件
try {
ImageIO.write(image, "png", new File(fileName));
System.out.println("艺术图片已生成!文件名为: " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}