/**
* 根据ImageView获适当的压缩的宽和高
*
* @param imageView
* @return
*/
public static ImageSize getImageViewSize(ImageView imageView)
{
ImageSize imageSize = new ImageSize();
DisplayMetrics displayMetrics = imageView.getContext().getResources()
.getDisplayMetrics();
LayoutParams lp = imageView.getLayoutParams();
int width = imageView.getWidth();// 获取imageview的实际宽度
if (width <= 0)
{
width = lp.width;// 获取imageview在layout中声明的宽度
}
if (width <= 0)
{
// width = imageView.getMaxWidth();// 检查最大值
width = getImageViewFieldValue(imageView, "mMaxWidth");
}
if (width <= 0)
{
width = displayMetrics.widthPixels;
}
int height = imageView.getHeight();// 获取imageview的实际高度
if (height <= 0)
{
height = lp.height;// 获取imageview在layout中声明的宽度
}
if (height <= 0)
{
height = getImageViewFieldValue(imageView, "mMaxHeight");// 检查最大值
}
if (height <= 0)
{
height = displayMetrics.heightPixels;
}
imageSize.width = width;
imageSize.height = height;
return imageSize;
}
public static class ImageSize
{
int width;
int height;
}
// 获得图片的宽和高,并不把图片加载到内存中
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
/**
* 根据需求的宽和高以及图片实际的宽和高计算SampleSize
*
* @param options
* @param width
* @param height
* @return
*/
public static int caculateInSampleSize(Options options, int reqWidth,
int reqHeight)
{
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if (width > reqWidth || height > reqHeight)
{
int widthRadio = Math.round(width * 1.0f / reqWidth);
int heightRadio = Math.round(height * 1.0f / reqHeight);
inSampleSize = Math.max(widthRadio, heightRadio);
}
return inSampleSize;
}
options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options,
width, height);
// 使用获得到的InSampleSize再次解析图片
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
return bitmap;
/**
* 根据url下载图片在指定的文件
*
* @param urlStr
* @param file
* @return
*/
public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview)
{
FileOutputStream fos = null;
InputStream is = null;
try
{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(conn.getInputStream());
is.mark(is.available());
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);
//获取imageview想要显示的宽和高
ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview);
opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts,
imageViewSize.width, imageViewSize.height);
opts.inJustDecodeBounds = false;
is.reset();
bitmap = BitmapFactory.decodeStream(is, null, opts);
conn.disconnect();
return bitmap;
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (is != null)
is.close();
} catch (IOException e)
{
}
try
{
if (fos != null)
fos.close();
} catch (IOException e)
{
}
}
return null;
}
public static ImageLoader getInstance(int threadCount, Type type)
{
if (mInstance == null)
{
synchronized (ImageLoader.class)
{
if (mInstance == null)
{
mInstance = new ImageLoader(threadCount, type);
}
}
}
return mInstance;
}
/**
* 图片加载类
*
* @author zhy
*
*/
public class ImageLoader
{
private static ImageLoader mInstance;
/**
* 图片缓存的核心对象
*/
private LruCache<String, Bitmap> mLruCache;
/**
* 线程池
*/
private ExecutorService mThreadPool;
private static final int DEAFULT_THREAD_COUNT = 1;
/**
* 队列的调度方式
*/
private Type mType = Type.LIFO;
/**
* 任务队列
*/
private LinkedList<Runnable> mTaskQueue;
/**
* 后台轮询线程
*/
private Thread mPoolThread;
private Handler mPoolThreadHandler;
/**
* UI线程中的Handler
*/
private Handler mUIHandler;
private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0);
private Semaphore mSemaphoreThreadPool;
private boolean isDiskCacheEnable = true;
private static final String TAG = "ImageLoader";
public enum Type
{
FIFO, LIFO;
}
private ImageLoader(int threadCount, Type type)
{
init(threadCount, type);
}
/**
* 初始化
*
* @param threadCount
* @param type
*/
private void init(int threadCount, Type type)
{
initBackThread();
// 获取我们应用的最大可用内存
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheMemory = maxMemory / 8;
mLruCache = new LruCache<String, Bitmap>(cacheMemory)
{
@Override
protected int sizeOf(String key, Bitmap value)
{
return value.getRowBytes() * value.getHeight();
}
};
// 创建线程池
mThreadPool = Executors.newFixedThreadPool(threadCount);
mTaskQueue = new LinkedList<Runnable>();
mType = type;
mSemaphoreThreadPool = new Semaphore(threadCount);
}
/**
* 初始化后台轮询线程
*/
private void initBackThread()
{
// 后台轮询线程
mPoolThread = new Thread()
{
@Override
public void run()
{
Looper.prepare();
mPoolThreadHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
// 线程池去取出一个任务进行执行
mThreadPool.execute(getTask());
try
{
mSemaphoreThreadPool.acquire();
} catch (InterruptedException e)
{
}
}
};
// 释放一个信号量
mSemaphorePoolThreadHandler.release();
Looper.loop();
};
};
mPoolThread.start();
}
/**
* 根据path为imageview设置图片
*
* @param path
* @param imageView
*/
public void loadImage(final String path, final ImageView imageView,
final boolean isFromNet)
{
imageView.setTag(path);
if (mUIHandler == null)
{
mUIHandler = new Handler()
{
public void handleMessage(Message msg)
{
// 获取得到图片,为imageview回调设置图片
ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
Bitmap bm = holder.bitmap;
ImageView imageview = holder.imageView;
String path = holder.path;
// 将path与getTag存储路径进行比较
if (imageview.getTag().toString().equals(path))
{
imageview.setImageBitmap(bm);
}
};
};
}
// 根据path在缓存中获取bitmap
Bitmap bm = getBitmapFromLruCache(path);
if (bm != null)
{
refreashBitmap(path, imageView, bm);
} else
{
addTask(buildTask(path, imageView, isFromNet));
}
}
private void refreashBitmap(final String path, final ImageView imageView,
Bitmap bm)
{
Message message = Message.obtain();
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = bm;
holder.path = path;
holder.imageView = imageView;
message.obj = holder;
mUIHandler.sendMessage(message);
}
// 将path与getTag存储路径进行比较
if (imageview.getTag().toString().equals(path))
{
imageview.setImageBitmap(bm);
}
private synchronized void addTask(Runnable runnable)
{
mTaskQueue.add(runnable);
// if(mPoolThreadHandler==null)wait();
try
{
if (mPoolThreadHandler == null)
mSemaphorePoolThreadHandler.acquire();
} catch (InterruptedException e)
{
}
mPoolThreadHandler.sendEmptyMessage(0x110);
}
mPoolThreadHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
// 线程池去取出一个任务进行执行
mThreadPool.execute(getTask());
/**
* 从任务队列取出一个方法
*
* @return
*/
private Runnable getTask()
{
if (mType == Type.FIFO)
{
return mTaskQueue.removeFirst();
} else if (mType == Type.LIFO)
{
return mTaskQueue.removeLast();
}
return null;
}
/**
* 根据传入的参数,新建一个任务
*
* @param path
* @param imageView
* @param isFromNet
* @return
*/
private Runnable buildTask(final String path, final ImageView imageView,
final boolean isFromNet)
{
return new Runnable()
{
@Override
public void run()
{
Bitmap bm = null;
if (isFromNet)
{
File file = getDiskCacheDir(imageView.getContext(),
md5(path));
if (file.exists())// 如果在缓存文件中发现
{
Log.e(TAG, "find image :" + path + " in disk cache .");
bm = loadImageFromLocal(file.getAbsolutePath(),
imageView);
} else
{
if (isDiskCacheEnable)// 检测是否开启硬盘缓存
{
boolean downloadState = DownloadImgUtils
.downloadImgByUrl(path, file);
if (downloadState)// 如果下载成功
{
Log.e(TAG,
"download image :" + path
+ " to disk cache . path is "
+ file.getAbsolutePath());
bm = loadImageFromLocal(file.getAbsolutePath(),
imageView);
}
} else
// 直接从网络加载
{
Log.e(TAG, "load image :" + path + " to memory.");
bm = DownloadImgUtils.downloadImgByUrl(path,
imageView);
}
}
} else
{
bm = loadImageFromLocal(path, imageView);
}
// 3、把图片加入到缓存
addBitmapToLruCache(path, bm);
refreashBitmap(path, imageView, bm);
mSemaphoreThreadPool.release();
}
};
}
private Bitmap loadImageFromLocal(final String path,
final ImageView imageView)
{
Bitmap bm;
// 加载图片
// 图片的压缩
// 1、获得图片需要显示的大小
ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView);
// 2、压缩图片
bm = decodeSampledBitmapFromPath(path, imageSize.width,
imageSize.height);
return bm;
}
/**
* 将图片加入LruCache
*
* @param path
* @param bm
*/
protected void addBitmapToLruCache(String path, Bitmap bm)
{
if (getBitmapFromLruCache(path) == null)
{
if (bm != null)
mLruCache.put(path, bm);
}
}
package com.example.demo_zhy_18_networkimageloader;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.zhy.utils.ImageLoader;
import com.zhy.utils.ImageLoader.Type;
import com.zhy.utils.Images;
public class ListImgsFragment extends Fragment
{
private GridView mGridView;
private String[] mUrlStrs = Images.imageThumbUrls;
private ImageLoader mImageLoader;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mImageLoader = ImageLoader.getInstance(3, Type.LIFO);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_list_imgs, container,
false);
mGridView = (GridView) view.findViewById(R.id.id_gridview);
setUpAdapter();
return view;
}
private void setUpAdapter()
{
if (getActivity() == null || mGridView == null)
return;
if (mUrlStrs != null)
{
mGridView.setAdapter(new ListImgItemAdaper(getActivity(), 0,
mUrlStrs));
} else
{
mGridView.setAdapter(null);
}
}
private class ListImgItemAdaper extends ArrayAdapter<String>
{
public ListImgItemAdaper(Context context, int resource, String[] datas)
{
super(getActivity(), 0, datas);
Log.e("TAG", "ListImgItemAdaper");
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = getActivity().getLayoutInflater().inflate(
R.layout.item_fragment_list_imgs, parent, false);
}
ImageView imageview = (ImageView) convertView
.findViewById(R.id.id_img);
imageview.setImageResource(R.drawable.pictures_no);
mImageLoader.loadImage(getItem(position), imageview, true);
return convertView;
}
}
}
<GridView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/id_gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:horizontalSpacing="3dp" android:verticalSpacing="3dp" android:numColumns="3" > </GridView> item_fragment_list_imgs.xml <ImageView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/id_img" android:layout_width="match_parent" android:layout_height="120dp" android:scaleType="centerCrop" > </ImageView>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有