- package imageView;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- /**
- * @說明 從網絡獲取圖片到本地
- * @author …………
- * @version 1.0
- * @since
- */
- public class GetImage {
- /**
- * 測試
- * @param args
- */
- public static void main(String[] args) {
- String url = "http://www.baidu.com/img/baidu_sylogo1.gif";
- byte[] btImg = getImageFromNetByUrl(url);
- if(null != btImg && btImg.length > 0){
- System.out.println("讀取到:" + btImg.length + " 字節");
- String fileName = "百度.gif";
- writeImageToDisk(btImg, fileName);
- }else{
- System.out.println("沒有從該連接獲得內容");
- }
- }
- /**
- * 將圖片寫入到磁盤
- * @param img 圖片數據流
- * @param fileName 文件保存時的名稱
- */
- public static void writeImageToDisk(byte[] img, String fileName){
- try {
- File file = new File("D:\\" + fileName);
- FileOutputStream fops = new FileOutputStream(file);
- fops.write(img);
- fops.flush();
- fops.close();
- System.out.println("圖片已經寫入到D盤");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 根據地址獲得數據的字節流
- * @param strUrl 網絡連接地址
- * @return
- */
- public static byte[] getImageFromNetByUrl(String strUrl){
- try {
- URL url = new URL(strUrl);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(5 * 1000);
- InputStream inStream = conn.getInputStream();//通過輸入流獲取圖片數據
- byte[] btImg = readInputStream(inStream);//得到圖片的二進制數據
- return btImg;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 從輸入流中獲取數據
- * @param inStream 輸入流
- * @return
- * @throws Exception
- */
- public static byte[] readInputStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while( (len=inStream.read(buffer)) != -1 ){
- outStream.write(buffer, 0, len);
- }
- inStream.close();
- return outStream.toByteArray();
- }
- }
資源圖片下載
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.