您的位置:首页 > 移动开发 > Android开发

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

2012-06-28 17:59 549 查看
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;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: