從服務器下載圖片保存到本地磁盤中

在做OCR時,我們會從服務器下載驗證碼圖片,可以通過把驗證碼圖片下載到本地保存起來使用。

以下是下載圖片的實現:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Test {
	public static final String URL_PATH = "http://member.0256.cn/Include/ASPX/CheckCode.aspx?rnd=0.7748341448605061"; // 實例圖片,實際開發中可能是獲得服務器上的所有圖片,或者部分圖片,不可能是具體某一張圖片

	// 把從服務器獲得圖片的輸入流InputStream寫到本地磁盤
	public static void saveImageToDisk() {
		InputStream inputStream = getInputStream();
		byte[] data = new byte[1024];
		int len = 0;
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream("F:\\checkCode.jpg");
			while ((len = inputStream.read(data)) != -1) {
				fileOutputStream.write(data, 0, len);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	// 從服務器獲得一個輸入流(本例是指從服務器獲得一個image輸入流)
	public static InputStream getInputStream() {
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL url = new URL(URL_PATH);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			// 設置網絡連接超時時間
			httpURLConnection.setConnectTimeout(3000);
			// 設置應用程序要從網絡連接讀取數據
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod("GET");
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode == 200) {
				// 從服務器返回一個輸入流
				inputStream = httpURLConnection.getInputStream();
				System.out.println(inputStream + "**********************");
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputStream;
	}

	public static void main(String args[]) {
		// 從服務器端獲得圖片,保存到本地
		saveImageToDisk();
//		File file = new File(
//				"C://Program Files//Apache Software Foundation//Tomcat 6.0//webapps//plpwmanagers//DpImg//"); // 得到服務器上DpImg文件下所有圖片
//		String test[];
//		test = file.list(); // 將每張圖片依次存放到 test 數組中
//
//		System.out.println(test.length);
//		for (int i = 0; i < test.length; i++) {
//			System.out.println(test[i]);
//		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章