JDK类库创建一张简单图片

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面试题与答案】整理推荐

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值