JDK类库创建一张简单图片
工具代码
/**
* 绘制图片
* @param bufferedImage 缓冲图片
* @param type 图片类型
* @param file 文件
* @throws IOException
*/
public static boolean drawSimpleImage(BufferedImage bufferedImage, String type, File file) throws IOException {
Graphics g = bufferedImage.getGraphics();//获取图片画笔
try {
int backgroundX = 10;//背景x坐标
int backgroundY = 40;//背景y坐标
int backgroundWith = 180;//背景宽
int backgroundHeight = 120;//背景高
g.fillRect(backgroundX, backgroundY, backgroundWith, backgroundHeight);//填充背景,默认白色
g.setColor(new Color(120, 120, 120));//设置画笔颜色
int fontSize = 28;//字体大小
g.setFont(new Font("宋体", Font.BOLD, fontSize));//设置字体
int stringX = 10;//文字x坐标
int stringY = 100;//文字y坐标
g.drawString("绘制简单图片", stringX, stringY);
return ImageIO.write(bufferedImage, type, file);
} finally {
g.dispose();//释放画笔
}
}
测试代码
private static final String IMAGE_PATH = PathUtil.getProjectPath() + File.separator + "images" + File.separator;
private static final String FILE_PATH = PathUtil.getProjectPath() + File.separator + "files" + File.separator;
/**
* 测试图片绘制
* @throws IOException
*/
@Test
public void testDrawImage() throws IOException {
BufferedImage bufferedImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_BGR);
File dir = new File(IMAGE_PATH);
if (!dir.exists()) {
dir.mkdirs();
}
ImageUtil.drawSimpleImage(bufferedImage, "jpg",
new File(IMAGE_PATH + "simple.jpg"));
}
生成的图片
完整源码:https://github.com/ConstXiong/xtools
【Java面试题与答案】整理推荐