Android加载网络图片的工具类
ImageView加载网络的图片
HttpUtil.java
- package com.eiice.httpuimagetils;
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import android.graphics.Bitmap;
- import android.util.Log;
- /**
- * @author 与网络连接的工具类
- *
- */
- public class HttpUtil {
- public static Bitmap download(String path){
- try{
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- InputStream in = conn.getInputStream();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int len = 0;
- byte buff[] = new byte[1024];
- while((len = in.read(buff)) > 0){
- out.write(buff, 0 ,len);
- }
- in.close();
- out.close();
- Log.e("test", "download:"+path);
- byte image[] = out.toByteArray();
- return ImageUtil.bytes2Bimap(image);
- }catch(Exception e){
- e.printStackTrace();
- return null;
- }
- }
- }
ImageLoader.java
- package com.eiice.httpuimagetils;
- import java.lang.ref.WeakReference;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.Random;
- import java.util.WeakHashMap;
- import android.graphics.Bitmap;
- import android.os.AsyncTask;
- import android.support.v4.util.LruCache;
- import android.util.Log;
- import android.widget.ImageView;
- /**
- * 本地图片加载,没有获取到网络的图片数据,就先显示本地的。得到网络的数据,再显示最新的。
- */
- public class ImageLoader {
- private static final String TAG = "ImageLoader";
- private ImageCache cache;
- private HashSet<String> cacheKeys = new HashSet<String>();
- private ImageDownloader downloader;
- private WeakHashMap<ImageView, String> imageView2FileMap = new WeakHashMap<ImageView, String>();
- private HashMap<String, HashSet<ImageViewReference>> file2ImageViewMap = new HashMap<String, HashSet<ImageViewReference>>();
- private HashSet<String> fileInLoadSet = new HashSet<String>();
- public ImageLoader(ImageDownloader downloader) {
- if(downloader == null){
- throw new RuntimeException("ImageDownloader can not be null");
- }
- this.cache = ImageCache.getInstance();
- this.downloader = downloader;
- }
- /**
- * @return 缓存中有,直接设置,并返回true,没有异步读取,读完再设置,返回false
- */
- public boolean loadImage(String filePath, int width, int height, ImageView imageView) {
- String filePathKey = getKeyForFilePath(filePath, width, height);
- Bitmap bmp = cache.get(filePathKey);
- if (bmp == null) {
- ImageViewReference imageViewRef = new ImageViewReference(imageView);
- // 更新imageView和filepath的最新的关系
- imageView2FileMap.put(imageView, filePathKey);
- HashSet<ImageViewReference> imageViewSet = file2ImageViewMap.get(filePathKey);
- if (imageViewSet == null) {
- imageViewSet = new HashSet<ImageViewReference>();
- file2ImageViewMap.put(filePathKey, imageViewSet);
- }
- imageViewSet.add(imageViewRef);
- // 防止重复下载
- if (fileInLoadSet.contains(filePathKey)) {
- return false;
- } else {
- fileInLoadSet.add(filePathKey);
- }
- Holder holder = new Holder();
- holder.width = width;
- holder.height = height;
- holder.filePath = filePath;
- holder.filePathKey = filePathKey;
- holder.imageViewRef = imageViewRef;
- new ImageLoadTask().execute(holder);
- return false;
- } else {
- imageView.setImageBitmap(bmp);
- return true;
- }
- }
- private class ImageLoadTask extends AsyncTask<Holder, Void, Holder> {
- @Override
- protected Holder doInBackground(Holder... params) {
- Holder holder = params[0];
- int width = holder.width;
- int height = holder.height;
- String filePath = holder.filePath;
- String filePathKey = holder.filePathKey;
- int count = getCountOfImageViewForKey(filePathKey);
- if (count <= 0) {
- return null;
- }
- try {
- Random rnd = new Random();
- Thread.sleep((int) (1000 * rnd.nextDouble()));
- } catch (Exception e) {
- e.printStackTrace();
- }
- if(downloader != null){
- Bitmap bmp = downloader.download(filePath, width, height);
- if(bmp != null){
- cache.put(filePathKey, bmp);
- cacheKeys.add(filePath);
- holder.imageData = bmp;
- }
- }
- return holder;
- }
- @Override
- protected void onPostExecute(Holder holder) {
- super.onPostExecute(holder);
- String filePathKey = holder.filePathKey;
- fileInLoadSet.remove(filePathKey);
- Bitmap data = holder.imageData;
- if(data == null){
- return;
- }
- ArrayList<ImageView> imageViewArrayList = getImageViewListForKey(filePathKey);
- if (imageViewArrayList.size() == 0) {
- return;
- }
- for (ImageView imageView : imageViewArrayList) {
- String latestFilePathKey = imageView2FileMap.get(imageView);
- if (latestFilePathKey != null && latestFilePathKey.equals(filePathKey)) {
- if (imageView != null) {
- imageView.setImageBitmap(data);
- Log.e(TAG, "设置图片 ");
- /*
- * boolean isSet;
- * try{
- * isSet=(Boolean)
- * imageView.getTag();
- * }catch(Exception e) {
- * isSet=true;
- * }
- * if(isSet) {
- * imageView.setImageBitmap(result);
- * Log.e(TAG,"设置图片 ");
- * }
- */
- }
- imageView2FileMap.remove(imageView);
- } else {
- }
- }
- file2ImageViewMap.remove(filePathKey);
- }
- }
- class Holder {
- int width,height;
- String filePath, filePathKey;
- Bitmap imageData;
- ImageViewReference imageViewRef;
- }
- private String getKeyForFilePath(String imagePath, int width, int height) {
- return imagePath + "_" + width + "_" + height;
- }
- /**
- * �?��ImageLoader
- *
- * */
- public void clear(){
- imageView2FileMap.clear();
- file2ImageViewMap.clear();
- fileInLoadSet.clear();
- for(String cacheKey : cacheKeys){
- cache.remove(cacheKey);
- }
- cacheKeys.clear();
- imageView2FileMap = null;
- file2ImageViewMap = null;
- fileInLoadSet = null;
- cacheKeys = null;
- downloader = null;
- cache = null;
- }
- /**
- * ImageLoader.java退出时调用
- *
- * */
- public void destory() {
- clear();
- ImageCache.destroy();
- }
- public interface ImageDownloader{
- public Bitmap download(String path,int width, int height);
- }
- /**
- * 通过file2ImageViewMap获取filePath对应的所有imageView列表 同时删除被回收的imageView,
- *
- * @param filePathKey
- * @return
- */
- private ArrayList<ImageView> getImageViewListForKey(String filePathKey) {
- ArrayList<ImageView> imageViewArrayList = new ArrayList<ImageView>();
- HashSet<ImageViewReference> imageViewReferences = file2ImageViewMap.get(filePathKey);
- if(imageViewReferences == null){
- return null;
- }
- Iterator<ImageViewReference> it = imageViewReferences.iterator();
- while (it.hasNext()) {
- ImageViewReference reference = it.next();
- if (reference.get() != null) {
- imageViewArrayList.add(reference.get());
- } else {
- it.remove();
- }
- }
- return imageViewArrayList;
- }
- /**
- * 获取指定的filePath对应的有效imageView的数据
- *
- * @param filePathKey
- * @return
- */
- private int getCountOfImageViewForKey(String filePathKey) {
- ArrayList<ImageView> imageViewArrayList = getImageViewListForKey(filePathKey);
- if(imageViewArrayList == null){
- return 0;
- }else{
- return imageViewArrayList.size();
- }
- }
- private static class ImageCache extends LruCache<String, Bitmap> {
- private static final int cacheSize = 10 * 1024 * 1024;
- private static ImageCache instance = new ImageCache(cacheSize);
- public static ImageCache getInstance(){
- return instance;
- }
- private ImageCache(int maxSize) {
- super(maxSize);
- }
- @Override
- protected int sizeOf(String key, Bitmap value) {
- return value.getByteCount();
- }
- public static void destroy(){
- if(instance == null){
- return;
- }
- instance.evictAll();
- instance = null;
- }
- }
- private static class ImageViewReference extends WeakReference<ImageView> {
- public ImageViewReference(ImageView r) {
- super(r);
- }
- @Override
- public boolean equals(Object o) {
- ImageViewReference other=(ImageViewReference)o;
- return this.get()==other.get();
- }
- @Override
- public int hashCode() {
- ImageView imageView = this.get();
- if(imageView != null){
- return imageView.hashCode();
- }
- return 0;
- }
- }
- }
ImageUtil.java
- package com.eiice.httpuimagetils;
- import java.io.ByteArrayOutputStream;
- import java.math.BigDecimal;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Matrix;
- import android.graphics.drawable.BitmapDrawable;
- import android.graphics.drawable.Drawable;
- import android.util.Log;
- public class ImageUtil {
- static final String TAG="ImageUtil";
- public static Bitmap compressPic2Bitmap(String picfullname) {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- Bitmap bitmap = BitmapFactory.decodeFile(picfullname, options); // 此时返回bm为空
- options.inJustDecodeBounds = false;
- int be = (int) (options.outHeight / (float) 200);
- if (be <= 0)
- be = 1;
- options.inSampleSize = be;
- bitmap = BitmapFactory.decodeFile(picfullname, options);
- return bitmap;
- }
- public static Drawable bitmap2Drawable(Bitmap bm) {
- BitmapDrawable bd = new BitmapDrawable(bm);
- return bd;
- }
- public static Drawable compressPic2Drawable(String picfullname) {
- return bitmap2Drawable(compressPic2Bitmap(picfullname));
- }
- public static Bitmap compressPic2Bitmap(Bitmap bitmap, int width, int height, boolean isAdjust) {
- if (bitmap.getWidth() < width && bitmap.getHeight() < height) {
- return bitmap;
- }
- float sx = new BigDecimal(width).divide(new BigDecimal(bitmap.getWidth()), 4, BigDecimal.ROUND_DOWN)
- .floatValue();
- float sy = new BigDecimal(height).divide(new BigDecimal(bitmap.getHeight()), 4, BigDecimal.ROUND_DOWN)
- .floatValue();
- if (isAdjust) {
- sx = (sx < sy ? sx : sy);
- sy = sx;
- }
- Matrix matrix = new Matrix();
- matrix.postScale(sx, sy);
- return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
- }
- public static Drawable compressPic2Drawable(String picfullname, int width, int height) {
- // Bitmap bitmap = compressPic2Bitmap(picfullname);
- // bitmap = compressPic2Bitmap(bitmap, width, height, true);
- Bitmap bitmap = compressBitmap(picfullname, width, height);
- return new BitmapDrawable(bitmap);
- }
- public static Bitmap compressBitmap(String path, int sdwidth, int sdheight) {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(path, options);
- options.inSampleSize = calculateSampleSize(options, sdwidth, sdheight);
- options.inJustDecodeBounds = false;
- options.inDither = false;
- options.inPreferredConfig = Bitmap.Config.RGB_565;
- return BitmapFactory.decodeFile(path, options);
- }
- public static int calculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
- final int height = options.outHeight;
- final int width = options.outWidth;
- int inSampleSize = 1;
- if (height > reqHeight || width > reqWidth) {
- final int heightRatio = Math.round((float) height / (float) reqHeight);
- final int widthRatio = Math.round((float) width / (float) reqWidth);
- inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
- }
- return inSampleSize;
- }
- /**
- * 有损压缩图片
- * @param filePath
- * @return
- */
- public static byte[] compressBitmap(String filePath) {
- Bitmap sourceBmp=BitmapFactory.decodeFile(filePath);
- if(sourceBmp!=null)
- {
- Log.e(TAG, "原大小"+sourceBmp.getByteCount());
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- sourceBmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
- sourceBmp.recycle();
- sourceBmp=null;
- //如果压缩后还大于10M,再压一次,这种情况一般不会出现
- if(baos.size()>10*1024*1024)
- {
- byte[] bytes=baos.toByteArray();
- Bitmap tempBmp=BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
- baos.reset();
- tempBmp.compress(Bitmap.CompressFormat.JPEG, 30, baos);
- tempBmp.recycle();
- tempBmp=null;
- }
- byte[] bytes=baos.toByteArray();
- Log.e(TAG, "压缩后大小"+bytes.length);
- return bytes;
- }else{
- return null;
- }
- }
- public static Bitmap bytes2Bimap(byte[] b) {
- if (b.length != 0) {
- return BitmapFactory.decodeByteArray(b, 0, b.length);
- } else {
- return null;
- }
- }
- }
测试代码:activity_main.xml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/imageview"
- android:layout_width="400dp"
- android:layout_height="400dp" />
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="show" />
- </LinearLayout>
MainActivity.java
- package com.eiice.cn;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ImageView;
- import com.eiice.httpuimagetils.HttpUtil;
- import com.eiice.httpuimagetils.ImageLoader;
- import com.eiice.httpuimagetils.ImageLoader.ImageDownloader;
- public class MainActivity extends Activity {
- private ImageLoader imageLoader;
- private ImageView imageview;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- imageview = (ImageView) findViewById(R.id.imageview);
- imageLoader = new ImageLoader(new ImageDownloader(){
- @Override
- public Bitmap download(String path, int width, int height) {
- return HttpUtil.download(path);
- }
- });
- }
- public void show(View view){
- String imagepath = "http://img4.duitang.com/uploads/blog/201309/30/20130930115633_h8BEL.thumb.600_0.jpeg";
- imageLoader.loadImage(imagepath , 50, 50, imageview);
- }
- @Override
- protected void onDestroy() {
- // TODO Auto-generated method stub
- super.onDestroy();
- imageLoader.destory();
- }
- }
Android加载网络图片的工具类的更多相关文章
- android html 图片处理类--加载富文本工具类
在android开发中,一些资讯类页面,里面有html标签和图片,html 标签一般通过Html.fromHtml方法,即可以解决,但是如果html 有图片标签,那么,Html.fromHtml 好像 ...
- Android加载网络图片报android.os.NetworkOnMainThreadException异常
Android加载网络图片大致可以分为两种,低版本的和高版本的.低版本比如4.0一下或者更低版本的API直接利用Http就能实现了: 1.main.xml <?xml version=" ...
- Java加载Properties配置文件工具类
Java加载Properties配置文件工具类 import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; ...
- Android加载网络图片学习过程
好多应用,像我们公司的<乘友>还有其他的<飞鸽><陌陌><啪啪>这些,几乎每一款应用都需要加载网络图片,那ToYueXinShangWan,这是比须熟练 ...
- android 加载网络图片
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...
- Android 加载网络图片设置到ImageView
下载图片后显示在ImageView中 //1.定义全局变量 private Handler handler; private String image_url; private Bitmap bitm ...
- 加载Properties文件工具类:LoadConfig
import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; impor ...
- Android中用双缓存技术,加载网络图片
最近在学校参加一个比赛,写的一个Android应用,里面要加载大量的网络图片,可是用传统的方法图片一多就会造成程序出现内存溢出而崩溃.因为自己也在学习中,所以看了很多博客和视频,然后参照这些大神的写源 ...
- Android Volley入门到精通:使用Volley加载网络图片
在上一篇文章中,我们了解了Volley到底是什么,以及它的基本用法.本篇文章中我们即将学习关于Volley更加高级的用法,如何你还没有看过我的上一篇文章的话,建议先去阅读Android Volley完 ...
随机推荐
- 二模 (6) day1
第一题: 设 S(N)表示 N 的各位数字之和,如 S(484)=4+8+4=16,S(22)=2+2=4.如果一个正整数 x满足 S(x*x)=S(x)*S(x),我们称 x 为 Rabbit Nu ...
- ros使用RPLIDAR激光雷达
1.首先下载RPLIDAR的驱动功能包 https://github.com/robopeak/rplidar_ros 2.然后解压放到~/catkin_ws/src目录下 3.执行catkin_ma ...
- [开发笔记]-页面切图、CSS前端设计、JS
这两天在学习页面的切图,样式设计,把学习过程中注意的地方记录下来. 一. input输入框点击时去掉外边框 一般在IE,firefox下,设置 border:0 none; 即可.但在chrome下, ...
- 【第41套测试题NOIP2007】【排序】【DP】【高精度】【树】【图上路径】
先说点题外话,这两天的入学考试,炸了……语文有史以来最差,数学有史以来最差……还有4科,估计全炸……悲痛的心情,来调程序.这套题是8.31考的,从昨天晚上开始改的,因为第三题迟迟不想写,才拖到了现在. ...
- <转载>DB2常用命令
1.数据库的启动.停止 db2start --启动 db2stop [force] --停止 2.与数据库的连接.断开 db2 CONNECT TO DBName [user UserI ...
- ModuleWorks免费下载使用方法大全
ModuleWorks为模拟机器的工具运转及(或)机床和车床材料的搬运提供了一整套解决方案. 模拟技术可以识别潜在的碰撞问题,允许在NC代码生成前进行除错检查,并且渐渐成为CAM处理方面必不可少的解决 ...
- java基础之 创建对象的几种方式
有4种显式地创建对象的方式: 1.用new语句创建对象,这是最常用的创建对象的方式. 2.运用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor ...
- Core Text概述
本文是我翻译的苹果官方文档<Core Text Overview> Core Text框架是高级的底层文字布局和处理字体的技术.它在Mac OS X v10.5 and iOS 3.2开始 ...
- POJ 3156 - Interconnect (概率DP+hash)
题意:给一个图,有些点之间已经连边,现在给每对点之间加边的概率是相同的,问使得整个图连通,加边条数的期望是多少. 此题可以用概率DP+并查集+hash来做. 用dp(i,j,k...)表示当前的每个联 ...
- How to Write Doc Comments for the Javadoc Tool
http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html This document describe ...