很多时候我们都用得到异步实时加载图片,方式很多,以下是方法之一,实现较为简单;
话不多说直接上代码
getImageWithUrlAsyncTask.class
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class getImageWithUrlAsyncTask extends AsyncTask<String, Integer, Bitmap> {
String Url;
int viewId = 0;
Bitmap bmp = null;
public getImageWithUrlAsyncTask(String Url, int viewId,getImageWithUrlAsyncTask.OnPostExecute onPostExecute) {
this.onPostExecute = onPostExecute;
this.Url = Url;
this.viewId = viewId;
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL myurl = new URL(Url);
Log.i("getURLimageAsyncTask", "URL: " + Url);
// 获得连接
HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
conn.setConnectTimeout(60*1000);//设置超时
conn.setDoInput(true);
conn.setUseCaches(false);//不缓存
conn.connect();
InputStream is = conn.getInputStream();//获得图片的数据流
if (position == -1) {
bmp = BitmapFactory.decodeStream(is);
} else {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize = 20;
bmp = BitmapFactory.decodeStream(is, null, options);
}
is.close();
return bmp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
onPostExecute.onPostExecute(viewId, bitmap);
}
OnPostExecute onPostExecute;
public interface OnPostExecute {
void onPostExecute(int viewId, Bitmap bitmap);
}
// 在得到InputStream之后,先将InputStream转化为字节数组,然后在使用decodeByteArray方法解析图片,先将InputStream流转为byte数组
private byte[] inputStream2ByteArr(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
}
inputStream.close();
outputStream.close();
return outputStream.toByteArray();
}
// 然后在调用如下代码实现解析图片的操作
private Bitmap decodeBitmap(InputStream is) throws IOException {
if (is == null) {
return null;
}
BitmapFactory.Options options = new BitmapFactory.Options();
//设置该属性可以不占用内存,并且能够得到bitmap的宽高等属性,此时得到的bitmap是空
options.inJustDecodeBounds = true;
byte[] data = inputStream2ByteArr(is);//将InputStream转为byte数组,可以多次读取
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
//设置计算得到的压缩比例
// options.inSampleSize = 1;
//设置为false,确保可以得到bitmap != null
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
return bitmap;
}
}
在需要的地方调用即可
new getImageWithUrlAsyncTask( url, viewId, new getImageWithUrlAsyncTask.OnPostExecute() {
@Override
public void onPostExecute(int viewId, Bitmap bitmap) {
}
}).execute();
版权声明:本文为qq_15327175原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。