package com.io.image.demo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 通过URL下载网络图片到本地
*/
public class DownLoadImageByHttp
{
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 通过URL下载网络图片到本地
*/
public class DownLoadImageByHttp
{
/**
* 把图片资源保存到本地
*
* @param urlPath 网络图片的地址
* @param localPath 保存到本地的图片路径
* @param fileName 图片的名称
*/
public void downLoadImageToDisk(String urlPath,String localPath, String fileName)
{
FileOutputStream fos = null;byte[] bytes = null;File file = null;try{
file = new File(localPath + File.separator + fileName);bytes = getImageFromNetByUrl(urlPath);fos = new FileOutputStream(file);fos.write(bytes);fos.flush();fos.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 通过URL获取网络图片
*
* @param urlPath 网络图片的地址
* @return
*/
private byte[] getImageFromNetByUrl(String urlPath)
{
HttpURLConnection httpConn = null;InputStream inStream = null;byte[] bytes = null;try{
URL url = new URL(urlPath);httpConn = (HttpURLConnection) url.openConnection();httpConn.setRequestMethod("GET");httpConn.setConnectTimeout(5*1000);httpConn.setDoInput(true);httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
inStream = httpConn.getInputStream();bytes = readInputStream(inStream);
}
return bytes;
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
/**
* 从输入流读取数据,写到输出流中
*
* @param inStream 图片的输入流数据
* @return
*/
private byte[] readInputStream(InputStream inStream)
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] bytes = new byte[1024];
int len = 0;
try
{
while((len=inStream.read(bytes)) != -1 ){
outStream.write(bytes, 0, len);
}
inStream.close();
}catch (IOException e){
e.printStackTrace();
}
return outStream.toByteArray();
}}