图片异步加载AsyncTask以及ListView中item加载图片缓存

当LIstView加载多张图片时使用Handler+Runnable有点不现实,可以用谷歌的AsyncTask,另外,如果所需加载的图片不需要很精细的控制的话也可以采用AsyncTask,还有就是Listview加载的图片将其存入缓存中,暂且没写将其存在sd卡中,如果每次刷新Listview都要加载图片那么用户体验和程序的性能,下面附上代码:

SingleImageTaskUtil.java单个或者多个不要求对图片进行精细操作的话可以使用此工具类

package com.loulijun.utils;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;


public class SingleImageTaskUtil extends AsyncTask<String, Void, Bitmap> {


private ImageView iv;


public SingleImageTaskUtil(ImageView iv) {
this.iv = iv;
}


@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bitmap = null;
try {
bitmap = SimpleImageLoader.getBitmap(params[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return bitmap;
}


@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);


if (result != null) {
iv.setImageBitmap(result);
}
}


@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}


public static class SimpleImageLoader {
public static Bitmap getBitmap(String urlStr) throws IOException {
Bitmap bitmap;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");//用户可以根据不同的需要选择不同的方法get或者post请求
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
}


}


ListViewImageTaskUtil.java当用户选择加载图片到Listview中可以选择此工具类操作,下面附上工具里代码,以及Listview的Adapter中的操作代码

package com.loulijun.utils;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;


public class ListViewImageTaskUtil extends AsyncTask<String, Void, Bitmap> {


private ImageView iv;
private LruCache<String, Bitmap> lruCache;//定义一个缓存区,程序被系统分配的


public ListViewImageTaskUtil(ImageView iv) {
this.iv = iv;
}


public ListViewImageTaskUtil(ImageView iv, LruCache<String, Bitmap> lruCache) {
super();
this.iv = iv;
this.lruCache = lruCache;
}


@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bitmap = null;
try {
bitmap = SimpleImageLoader.getBitmap(params[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addBitmapToMemoryCache(params[0], bitmap);
return bitmap;
}


@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);


if (result != null) {
iv.setImageBitmap(result);
}
}


@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}


private void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemoryCache(key) == null) {
lruCache.put(key, bitmap);
}
}


public Bitmap getBitmapFromMemoryCache(String key) {
return lruCache.get(key);
}


public static class SimpleImageLoader {
public static Bitmap getBitmap(String urlStr) throws IOException {
Bitmap bitmap;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
}


}


MyAdapter.java下面是Adapter代码

package com.loulijun.adapter;


import java.util.List;


import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.loulijun.bean.CommondBean;
import com.loulijun.logindemo.R;
import com.loulijun.utils.ListViewImageTaskUtil;


public class MyAdapter extends BaseAdapter {


private Context context;


private List<CommondBean> commondBeans;


// 获取当前应用程序所分配的最大内存
private final int maxMemory = (int) Runtime.getRuntime().maxMemory();
// 只用五分之一用来做图片缓存
private final int cacheSize = maxMemory / 5;


private LruCache<String, Bitmap> mLruCache = new LruCache<String, Bitmap>(
cacheSize) {


// 重写sizeof()方法
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// TODO Auto-generated method stub
// 这里用多少kb来计算
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}


};


public MyAdapter(Context context, List<CommondBean> commondBeans) {


this.context = context;
this.commondBeans = commondBeans;
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return commondBeans.size();
}


@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return commondBeans.get(position);
}


@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub


View view = convertView;


ViewHolder holder = null;


if (view == null) {
view = LayoutInflater.from(context).inflate(
R.layout.item_listview_commond, null);


holder = new ViewHolder();
view.setTag(holder);


holder.user_img = (ImageView) view.findViewById(R.id.userimg);
holder.user_detail = (TextView) view.findViewById(R.id.detail);
holder.user_name = (TextView) view.findViewById(R.id.name);
holder.user_good = (Button) view.findViewById(R.id.good);
holder.user_good.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub


Toast.makeText(context, "32个赞!", Toast.LENGTH_SHORT).show();


}
});
holder.user_poor = (Button) view.findViewById(R.id.poor);
holder.user_poor.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "贬低一个!", Toast.LENGTH_SHORT).show();
}
});
holder.user_hot = (Button) view.findViewById(R.id.hot);
holder.user_hot.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "更加火爆!", Toast.LENGTH_SHORT).show();
}
});
holder.user_share = (Button) view.findViewById(R.id.share);
holder.user_share.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "分享成功!", Toast.LENGTH_SHORT).show();
}
});
holder.good = (TextView) view.findViewById(R.id.goodtext);
holder.poor = (TextView) view.findViewById(R.id.poortext);
holder.hot = (TextView) view.findViewById(R.id.hottext);
holder.share = (TextView) view.findViewById(R.id.sharetext);


} else {
holder = (ViewHolder) convertView.getTag();
}


holder.user_detail.setText(commondBeans.get(position).getUserDetail());
holder.user_name.setText(commondBeans.get(position).getUserName());
holder.good.setText(commondBeans.get(position).getGood());
holder.poor.setText(commondBeans.get(position).getPoor());
holder.hot.setText(commondBeans.get(position).getHot());
holder.share.setText(commondBeans.get(position).getShare());
// 多任务处理加载图片
// ListViewImageTaskUtil imageTask = new ListViewImageTaskUtil(holder.user_img);
// imageTask.execute(commondBeans.get(position).getUserImg());
loadBitmap(commondBeans.get(position).getUserImg(), holder.user_img);
return view;
}


static class ViewHolder {
ImageView user_img;
TextView user_name;
TextView user_detail;
TextView good;
TextView poor;
TextView hot;
TextView share;
Button user_good;
Button user_poor;
Button user_hot;
Button user_share;
}


private void loadBitmap(String urlStr, ImageView image) {


ListViewImageTaskUtil asyncLoader = new ListViewImageTaskUtil(image, mLruCache);// 一个异步图片加载对象
Bitmap bitmap = asyncLoader.getBitmapFromMemoryCache(urlStr);// 首先从内存缓存中获取图片
if (bitmap != null) {
image.setImageBitmap(bitmap);// 如果缓存中存在这张图片则直接设置给ImageView
} else {
image.setImageResource(R.drawable.dufu);// 否则先设置成默认的图片
asyncLoader.execute(urlStr);// 然后执行异步任务AsycnTask 去网上加载图片
}
}


}


这两个工具类可以满足大部分的需求,如需对图片进行更为精细的操作大家可以自定义handler+Runnable

深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值