View Code
public static Bitmap downloadBitmap(String imageUrl) {
Log.d("try to download image","imageUrl:"+imageUrl);
URL url = null;
Bitmap bitmap = null;
try {
/* new URL对象将网址传入 */
url = new URL(imageUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
try {
/* 取得连接 */
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.connect();
/* 取得返回的InputStream */
InputStream is = conn.getInputStream();
/* 将InputStream变成Bitmap */
bitmap = BitmapFactory.decodeStream(is);
/* 关闭InputStream */
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
有时候,需要对下载下来的图片调整大小:
View Code
public static Drawable resizeImage(Bitmap bitmap, int w, int h) {
Bitmap BitmapOrg = bitmap;
int width = BitmapOrg.getWidth();
int height = BitmapOrg.getHeight();
int newWidth = w;
int newHeight = h;
// calculate the scale
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the Bitmap
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return new BitmapDrawable(resizedBitmap);
}