这里我写的是读取单张的图片从网络读取,和listview多张图片的读取首先是单张的读取这篇博客只写了读取单张的读取多张的下一篇写 此例子的代码 已上传资源页
由于昨天时间比较紧所以,这个Demo 的源码中好像是忘了添加权限,抱歉。希望大家下载以后自己在源码的androidManifest.xml中添加网络访问和SD读写权限
http://download.csdn.net/detail/u012373815/9002225
准备:在androidManifest.xml中添加权限
<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!--sd卡权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
</uses-permission>
import java.io.File;
importandroid.content.Context;
publicclassFileCache {
privateFilecacheDir;
publicFileCache(Context context){
//找一个用来缓存图片的路径
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
publicFile getFile(String url){
String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
publicvoidclear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.example.imageloaddemo.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
importandroid.widget.ImageView;
publicclassImageLoader {
MemoryCache memoryCache=newMemoryCache();
FileCache fileCache;
privateMap<ImageView, String>imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView,String>());
ExecutorService executorService;
publicImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
finalintstub_id= R.drawable.ic_launcher; //没有图片
publicvoidDisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
//存在
imageView.setImageBitmap(bitmap);
else
{ //不存在
queuePhoto(url,imageView);
imageView.setImageResource(stub_id);
}
}
privatevoidqueuePhoto(String url, ImageView imageView)
{ Log.i("ImageLoader","00000000000000");
PhotoToLoad p=new PhotoToLoad(url,imageView);
executorService.submit(new PhotosLoader(p));
}
privateBitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
Log.i("ImageLoader","222222222222222");
//从sd加载
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//从网络加载
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
Log.i("ImageLoader",url+"aaaaaaaaaaa");
HttpURLConnection conn =(HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
int code=conn.getResponseCode();
if(code==200)
{
Log.i("ImageLoader","33333333333333");
}
InputStreamis=conn.getInputStream();
Log.i("ImageLoader",is+"is555555555555");
OutputStream os = newFileOutputStream(f);
Log.i("ImageLoader",bitmap+"555555555555");
Utils.CopyStream(is,os);
os.close();
bitmap = decodeFile(f);
Log.i("ImageLoader",bitmap+"555555555555");
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
returnnull;
}
}
//解码图像用来减少内存消�??
privateBitmap decodeFile(File f){
try {
//解码图像大小
BitmapFactory.Options o =newBitmapFactory.Options();
o.inJustDecodeBounds =true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//找到正确的刻度�?�,它应该是2的幂�?
finalint REQUIRED_SIZE=140; //解缩大小
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE ||height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options o2 =newBitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f),null, o2);
} catch (FileNotFoundException e) {}
returnnull;
}
//任务队列
privateclassPhotoToLoad
{
public Stringurl;
public ImageViewimageView;
public PhotoToLoad(String u, ImageViewi){
url=u;
imageView=i;
}
}
classPhotosLoaderimplements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoadphotoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
publicvoid run() {
Log.i("ImageLoader","11111111");
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp,photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
booleanimageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
returntrue;
returnfalse;
}
//用于显示位图在UI线程
classBitmapDisplayerimplements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b,PhotoToLoad p){bitmap=b;photoToLoad=p;}
publicvoid run()
{ Log.i("ImageLoader","2222222");
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
publicvoidclearCache() {
memoryCache.clear();
fileCache.clear();
}
}
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
importandroid.graphics.Bitmap;
// ④程序缓存的处理,主要是内存缓存+文件缓存。内存缓存中网上很多是采用SoftReference来防止堆溢出
publicclassMemoryCache {
privateMap<String,SoftReference<Bitmap>>cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());/
publicBitmap get(Stringid){
if(!cache.containsKey(id))
returnnull;
SoftReference<Bitmap> ref=cache.get(id);
return ref.get();
}
publicvoidput(String id,Bitmap bitmap){
cache.put(id, new SoftReference<Bitmap>(bitmap));
}
publicvoidclear() {
cache.clear();
}
}
import java.io.InputStream;
importjava.io.OutputStream;
//读取流的工具类,Utils.java?
publicclassUtils {
publicstaticvoidCopyStream(InputStream is, OutputStream os)
{
finalint buffer_size=1024;
try
{ Log.i("ImageLoader","4444444444444");
byte[] bytes=newbyte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
publicclassMainActivity extends Activity {
private ImageLoaderimage;
private Buttonbuttonimg;
private ImageViewimageloder;
String path;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageloder=(ImageView)findViewById(R.id.imageloder);
buttonimg=(Button)findViewById(R.id.buttonimg);
buttonimg.setOnClickListener(new OnClickListener() {
@Override
publicvoid onClick(View v) {
path="http://acm.hpu.edu.cn/backtow/imagething/1428379408250.jpg";
image=newImageLoader(MainActivity.this);
image.DisplayImage(path, imageloder);
}
});
}
}