java根据http url下载图片

版权声明:转载请注名出处 https://blog.csdn.net/meism5/article/details/88388062

网络图片下载

工具代码

/**
	 * 网络图片下载
	 * @param url 图片url
	 * @param formatName 文件格式名称
	 * @param localFile 下载到本地文件
	 * @return 下载是否成功
	 */
	public static boolean downloadImage(String imageUrl, String formatName, File localFile) {
		boolean isSuccess = false;
		URL url = null;
		try {
			url = new URL(imageUrl);
			isSuccess = ImageIO.write(ImageIO.read(url), formatName, localFile);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return isSuccess;
	}

测试代码

/**
	 * 测试图片下载
	 */
	@Test
	public void testDownloadImage() {
		String baiduLogoUrl = "https://www.baidu.com/img/bd_logo1.png";
		File localFile = new File(IMAGE_PATH + "bd_logo1.png");
		Assert.assertTrue(ImageUtil.downloadImage(baiduLogoUrl, ImageUtil.PNG, localFile));
	}

完整源码:https://github.com/ConstXiong/xtools

猜你喜欢

转载自blog.csdn.net/meism5/article/details/88388062