之前写的在Windows下无问题,但在Linux下运行报错,试了多种方法未解决,之所以改了代码在附上。
相关阅读:Java取网络图片并缩小
public boolean saveUrlAs() //fileUrl网络资源地址 { String fileName = "123.jpg"; String savePath="e:\"; String fileUrl=http://www.baidu.com/1.jpg; try { // 将网络资源地址传给,即赋值给url URL url = new URL(fileUrl); //此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); BufferedImage src = javax.imageio.ImageIO.read(in); // 边长缩小为二分之一 BufferedImage tag = new BufferedImage(156, 117, BufferedImage.TYPE_INT_RGB); // 绘制缩小后的图 Graphics g = tag.getGraphics(); g.drawImage(src,0,0,156,117,null); g.dispose(); File f = new File(savePath); ImageIO.write(tag, "jpeg", f); return true; //网络资源截取并存储本地成功返回true } catch (Exception e) { System.out.println(e); return false; } }