异步读取图片转换成bitmap
异步类
class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Void... params) {
InputStream inStream = null;
Bitmap bmp = null;
try {
java.net.URL url2 = new java.net.URL(imgurl);
URLConnection conn = url2.openConnection();
conn.setConnectTimeout(10 * 1000);
inStream = conn.getInputStream();
bmp = BitmapFactory.decodeStream(inStream);
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result == null) {
return;
}
img_foot_img.setImageBitmap(result);
}
}
2,将图片url转换成bitmap
public static Bitmap loadImageFromUrl(String url) throws Exception {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
HttpResponse response = client.execute(getRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.e("PicShow", "Request URL failed, error code =" + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity == null) {
Log.e("PicShow", "HttpEntity is null");
}
InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
is = entity.getContent();
byte[] buf = new byte[1024];
int readBytes = -1;
while ((readBytes = is.read(buf)) != -1) {
baos.write(buf, 0, readBytes);
}
} finally {
if (baos != null) {
baos.close();
}
if (is != null) {
is.close();
}
}
byte[] imageArray = baos.toByteArray();
return BitmapFactory.decodeByteArray(
imageArray, 0, imageArray.length);
}
3,保存bitmap到文件
private static void savePic(Bitmap b, String strFileName) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(strFileName);
if (null != fos) {
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}