从网络上下载图片到本地 可以使用 ImageIO 类来实现
其核心代码如下
// 创建一个网络上的图片所在路径
URL url = new URL(urlstr);
BufferedImage image = ImageIO.read(url);
// 将其以某种格式写入到本地,目前支持 jpg,gif,png 三种格式
ImageIO.write(image, "jpg", new File("D:\\temp\\a.jpg"));
ImageIO.write(image, "gif", new File("D:\\temp\\a.gif"));
ImageIO.write(image, "png", new File("D:\\temp\\a.png"));
实例如下:
public static void main(String[] args)
{
BufferedImage image = null;
try
{
String urlstr = "http://p15.qhimg.com/t01fad4e1f6a4b4f178.jpg";
String picname = "wl" + String.valueOf(System.currentTimeMillis()) + ".jpg";
String rootPath = System.getProperty("user.dir");
File savedFile = new File(rootPath, picname);
System.out.println(savedFile.getAbsolutePath());
URL url = new URL(urlstr);
image = ImageIO.read(url);
if (image != null)
{
ImageIO.write(image, "jpg", savedFile);
}
else
{
System.out.println("image null");
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}