【android】简单的根据url下载图片的一个类




import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;


public class DownloadFileUtil {


public static Bitmap downloadFile( String url) {
Bitmap bitmap = null;

try {
/*// //////////////取得的是byte数组, 从byte数组生成bitmap
byte[] data = getImage(url);
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);// bitmap
imageView.setImageBitmap(bitmap);// display image
} else {
// Toast.makeText(AndroidTest2_3_3.this, "Image error!",
// 1).show();
}*/


// ******** 取得的是InputStream,直接从InputStream生成bitmap ***********/
bitmap = BitmapFactory.decodeStream(getImageStream(url));



// ********************************************************************/

} catch (Exception e) {
//Toast.makeText(AndroidTest2_3_3.this, "Newwork error!", 1).show();
e.printStackTrace();
}
return bitmap;
}


private static byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(inStream);
}
return null;
}


private static byte[] readStream(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);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}


private static InputStream getImageStream(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
return null;
}


}

你可能感兴趣的:(android,exception,url,buffer,Path,byte)