import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class ImageRequest{/** * 讀取網絡圖片并保存至服務器硬盤中 * @param imgUrl * @return 圖片保存的服務器路徑 */public static String getImages(String imgUrl){String imgPath = "";try{ //new一個URL對象 URL url = new URL(imgUrl); //打開鏈接 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //設置請求方式為"GET" conn.setRequestMethod("GET"); //超時響應時間為5秒 conn.setConnectTimeout(5 * 1000); //通過輸入流獲取圖片數據 InputStream inStream = conn.getInputStream(); //得到圖片的二進制數據,以二進制封裝得到數據,具有通用性 byte[]data = readInputStream(inStream); imgPath = ImageRequest.class.getClassLoader().getResource("").getPath(); imgPath = imgPath.split("WEB-INF")[0]; imgPath = imgPath+"images/"+"haha.jpg"; //new一個文件對象用來保存圖片,默認保存當前工程根目錄 File imageFile = new File(imgPath); //創建輸出流 FileOutputStream outStream = new FileOutputStream(imageFile); //寫入數據 outStream.write(data); //關閉輸出流 outStream.close(); //服務器文件路徑 imgPath = imgPath.split("WebRoot")[1]; System.out.PRintln(imgPath);}catch(Exception e){e.printStackTrace();}return imgPath;} /** * 讀取文件流 * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //創建一個Buffer字符串 byte[] buffer = new byte[1024]; //每次讀取的字符串長度,如果為-1,代表全部讀取完畢 int len = 0; //使用一個輸入流從buffer里把數據讀取出來 while( (len=inStream.read(buffer)) != -1 ){ //用輸出流往buffer里寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度 outStream.write(buffer, 0, len); } //關閉輸入流 inStream.close(); //把outStream里的數據寫入內存 return outStream.toByteArray(); } public static void main(String[] args) throws Exception { ImageRequest.getImages("http://image.meilele.com/images/201311/1385338928366387259.jpg"); }}
|
新聞熱點
疑難解答