之前寫的在Windows下無問題,但在Linux下運行報錯,試了多種方法未解決,之所以改了代碼在附上。
相關閱讀:Java取網絡圖片並縮小 http://www.linuxidc.com/Linux/2012-02/55469.htm
- 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;
- }
- }