异步线程加载图片工具类


/**
 * 异步线程加载图片工具类 使用说明: BitmapManager bmpManager; bmpManager = new
 * BitmapManager(BitmapFactory.decodeResource(context.getResources(),
 * R.drawable.loading)); bmpManager.loadBitmap(imageURL, imageView);
 *
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-6-25
 */
public class BitmapManager {

    private static HashMap<String, SoftReference<Bitmap>> cache;
    private static ExecutorService pool;
    private static Map<ImageView, String> imageViews;
    private Bitmap defaultBmp;

    static {
        cache = new HashMap<String, SoftReference<Bitmap>>();
        pool = Executors.newFixedThreadPool(5); // 固定线程池
        imageViews = Collections
                .synchronizedMap(new WeakHashMap<ImageView, String>());
    }

    public BitmapManager() {
    }

    public BitmapManager(Bitmap def) {
        this.defaultBmp = def;
    }

    /**
     * 设置默认图片
     *
     * @param bmp
     */
    public void setDefaultBmp(Bitmap bmp) {
        defaultBmp = bmp;
    }

    /**
     * 加载图片
     *
     * @param url
     * @param imageView
     */
    public void loadBitmap(String url, ImageView imageView,float roundpx) {
        loadBitmap(url, imageView, this.defaultBmp, 0, 0,roundpx);
    }

    /**
     * 加载图片-可设置加载失败后显示的默认图片
     *
     * @param url
     * @param imageView
     * @param defaultBmp
     */
    public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp) {
        loadBitmap(url, imageView, defaultBmp, 0, 0,0);
    }

    /**
     * 加载图片-可指定显示图片的高宽
     *
     * @param url
     * @param imageView
     * @param width
     * @param height
     */
    public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp,
            int width, int height,float roundpx) {
        imageViews.put(imageView, url);
        Bitmap bitmap = getBitmapFromCache(url);

        if (bitmap != null) {
            // 显示缓存图片
            imageView.setImageBitmap(bitmap);
        } else {
            // 加载SD卡中的图片缓存
            String filename = FileUtils.getFileName(url);
            String filepath = imageView.getContext().getFilesDir()
                    + File.separator + filename;
            File file = new File(filepath);
            if (file.exists()) {
                // 显示SD卡中的图片缓存
                Bitmap bmp = ImageUtil.getBitmap(imageView.getContext(),
                        filename);
                imageView.setImageBitmap(bmp);
            } else {
                // 线程加载网络图片
                imageView.setImageBitmap(defaultBmp);
                queueJob(url, imageView, width, height,roundpx);
            }
        }
    }
    
    public void loadBitmap(String url, ImageView imageView, int bitmapresource,
            int width, int height,float roundpx) {
        imageViews.put(imageView, url);
        Bitmap bitmap = getBitmapFromCache(url);

        if (bitmap != null) {
            // 显示缓存图片
            imageView.setImageBitmap(bitmap);
        } else {
            // 加载SD卡中的图片缓存
            String filename = FileUtils.getFileName(url);
            String filepath = imageView.getContext().getFilesDir()
                    + File.separator + filename;
            File file = new File(filepath);
            if (file.exists()&&!file.isDirectory()) {
                // 显示SD卡中的图片缓存
                Bitmap bmp = ImageUtil.getBitmap(imageView.getContext(),
                        filename);
                imageView.setImageBitmap(bmp);
            } else {
                // 线程加载网络图片
                Bitmap defaultbm = BitmapFactory.decodeResource(imageView.getResources(), R.drawable.defaulthead);
                imageView.setImageBitmap(ImageUtil.getRoundedCornerBitmap(defaultbm, roundpx));
//                imageView.setImageResource(bitmapresource);
                if(url!=null&&!"".equals(url)){
                    queueJob(url, imageView, width, height,roundpx);
                }
            }
        }
    }


    /**
     * 从缓存中获取图片
     *
     * @param url
     */
    public Bitmap getBitmapFromCache(String url) {
        Bitmap bitmap = null;
        if (cache.containsKey(url)) {
            bitmap = cache.get(url).get();
        }
        return bitmap;
    }

    /**
     * 从网络中加载图片
     *
     * @param url
     * @param imageView
     * @param width
     * @param height
     */
    public void queueJob(final String url, final ImageView imageView,
            final int width, final int height,final float roundpx) {
        /* Create handler in UI thread. */
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                String tag = imageViews.get(imageView);
                if (tag != null && tag.equals(url)) {
                    if (msg.obj != null) {
                        imageView.setImageBitmap((Bitmap) msg.obj);
                        try {
                            // 向SD卡中写入图片缓存
                            ImageUtil.saveImage(imageView.getContext(),
                                    FileUtils.getFileName(url),
                                    (Bitmap) msg.obj);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        pool.execute(new Runnable() {
            public void run() {
                Message message = Message.obtain();
                message.obj = downloadBitmap(url, width, height,roundpx);
                handler.sendMessage(message);
            }
        });
    }

    /**
     * 下载图片-可指定显示图片的高宽
     *
     * @param url
     * @param width
     * @param height
     */
    private Bitmap downloadBitmap(String url, int width, int height,float roundpx) {
        Bitmap bitmap = null;
        URL myFileURL = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            // http加载图片
            myFileURL = new URL(url);
            // 获得连接
            conn = (HttpURLConnection) myFileURL.openConnection();
            // 设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            // 连接设置获得数据流
            conn.setDoInput(true);
            // 不使用缓存
            conn.setUseCaches(false);
            // 这句可有可无,没有影响
            // conn.connect();
            // 得到数据流
            is = conn.getInputStream();
            // 解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            
            bitmap = ImageUtil.getRoundedCornerBitmap(bitmap, roundpx);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != conn)
                conn.disconnect();
        }
        return bitmap;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值