ImageView加载网络的图片

HttpUtil.java

  1. package com.eiice.httpuimagetils;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7.  
  8. import android.graphics.Bitmap;
  9. import android.util.Log;
  10.  
  11. /**
  12. * @author 与网络连接的工具类
  13. *
  14. */
  15. public class HttpUtil {
  16.  
  17. public static Bitmap download(String path){
  18. try{
  19. URL url = new URL(path);
  20. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  21. InputStream in = conn.getInputStream();
  22. ByteArrayOutputStream out = new ByteArrayOutputStream();
  23. int len = 0;
  24. byte buff[] = new byte[1024];
  25. while((len = in.read(buff)) > 0){
  26. out.write(buff, 0 ,len);
  27. }
  28. in.close();
  29. out.close();
  30. Log.e("test", "download:"+path);
  31. byte image[] = out.toByteArray();
  32. return ImageUtil.bytes2Bimap(image);
  33. }catch(Exception e){
  34. e.printStackTrace();
  35. return null;
  36. }
  37. }
  38. }

ImageLoader.java

  1. package com.eiice.httpuimagetils;
  2.  
  3. import java.lang.ref.WeakReference;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.HashSet;
  7. import java.util.Iterator;
  8. import java.util.Random;
  9. import java.util.WeakHashMap;
  10.  
  11. import android.graphics.Bitmap;
  12. import android.os.AsyncTask;
  13. import android.support.v4.util.LruCache;
  14. import android.util.Log;
  15. import android.widget.ImageView;
  16.  
  17. /**
  18. * 本地图片加载,没有获取到网络的图片数据,就先显示本地的。得到网络的数据,再显示最新的。
  19. */
  20. public class ImageLoader {
  21.  
  22. private static final String TAG = "ImageLoader";
  23.  
  24. private ImageCache cache;
  25.  
  26. private HashSet<String> cacheKeys = new HashSet<String>();
  27.  
  28. private ImageDownloader downloader;
  29.  
  30. private WeakHashMap<ImageView, String> imageView2FileMap = new WeakHashMap<ImageView, String>();
  31. private HashMap<String, HashSet<ImageViewReference>> file2ImageViewMap = new HashMap<String, HashSet<ImageViewReference>>();
  32. private HashSet<String> fileInLoadSet = new HashSet<String>();
  33.  
  34. public ImageLoader(ImageDownloader downloader) {
  35. if(downloader == null){
  36. throw new RuntimeException("ImageDownloader can not be null");
  37. }
  38. this.cache = ImageCache.getInstance();
  39. this.downloader = downloader;
  40. }
  41.  
  42. /**
  43. * @return 缓存中有,直接设置,并返回true,没有异步读取,读完再设置,返回false
  44. */
  45. public boolean loadImage(String filePath, int width, int height, ImageView imageView) {
  46. String filePathKey = getKeyForFilePath(filePath, width, height);
  47. Bitmap bmp = cache.get(filePathKey);
  48. if (bmp == null) {
  49. ImageViewReference imageViewRef = new ImageViewReference(imageView);
  50. // 更新imageView和filepath的最新的关系
  51. imageView2FileMap.put(imageView, filePathKey);
  52. HashSet<ImageViewReference> imageViewSet = file2ImageViewMap.get(filePathKey);
  53. if (imageViewSet == null) {
  54. imageViewSet = new HashSet<ImageViewReference>();
  55. file2ImageViewMap.put(filePathKey, imageViewSet);
  56. }
  57. imageViewSet.add(imageViewRef);
  58. // 防止重复下载
  59. if (fileInLoadSet.contains(filePathKey)) {
  60. return false;
  61. } else {
  62. fileInLoadSet.add(filePathKey);
  63. }
  64. Holder holder = new Holder();
  65. holder.width = width;
  66. holder.height = height;
  67. holder.filePath = filePath;
  68. holder.filePathKey = filePathKey;
  69. holder.imageViewRef = imageViewRef;
  70. new ImageLoadTask().execute(holder);
  71. return false;
  72. } else {
  73. imageView.setImageBitmap(bmp);
  74. return true;
  75. }
  76.  
  77. }
  78.  
  79. private class ImageLoadTask extends AsyncTask<Holder, Void, Holder> {
  80.  
  81. @Override
  82. protected Holder doInBackground(Holder... params) {
  83. Holder holder = params[0];
  84. int width = holder.width;
  85. int height = holder.height;
  86. String filePath = holder.filePath;
  87. String filePathKey = holder.filePathKey;
  88. int count = getCountOfImageViewForKey(filePathKey);
  89. if (count <= 0) {
  90. return null;
  91. }
  92. try {
  93. Random rnd = new Random();
  94. Thread.sleep((int) (1000 * rnd.nextDouble()));
  95. } catch (Exception e) {
  96. e.printStackTrace();
  97. }
  98. if(downloader != null){
  99. Bitmap bmp = downloader.download(filePath, width, height);
  100. if(bmp != null){
  101. cache.put(filePathKey, bmp);
  102. cacheKeys.add(filePath);
  103. holder.imageData = bmp;
  104. }
  105. }
  106. return holder;
  107. }
  108.  
  109. @Override
  110. protected void onPostExecute(Holder holder) {
  111. super.onPostExecute(holder);
  112. String filePathKey = holder.filePathKey;
  113. fileInLoadSet.remove(filePathKey);
  114.  
  115. Bitmap data = holder.imageData;
  116. if(data == null){
  117. return;
  118. }
  119.  
  120. ArrayList<ImageView> imageViewArrayList = getImageViewListForKey(filePathKey);
  121. if (imageViewArrayList.size() == 0) {
  122. return;
  123. }
  124. for (ImageView imageView : imageViewArrayList) {
  125. String latestFilePathKey = imageView2FileMap.get(imageView);
  126. if (latestFilePathKey != null && latestFilePathKey.equals(filePathKey)) {
  127. if (imageView != null) {
  128. imageView.setImageBitmap(data);
  129. Log.e(TAG, "设置图片 ");
  130. /*
  131. * boolean isSet;
  132. * try{
  133. * isSet=(Boolean)
  134. * imageView.getTag();
  135. * }catch(Exception e) {
  136. * isSet=true;
  137. * }
  138. * if(isSet) {
  139. * imageView.setImageBitmap(result);
  140. * Log.e(TAG,"设置图片 ");
  141. * }
  142. */
  143. }
  144. imageView2FileMap.remove(imageView);
  145. } else {
  146.  
  147. }
  148. }
  149. file2ImageViewMap.remove(filePathKey);
  150. }
  151. }
  152.  
  153. class Holder {
  154. int width,height;
  155. String filePath, filePathKey;
  156. Bitmap imageData;
  157. ImageViewReference imageViewRef;
  158. }
  159.  
  160. private String getKeyForFilePath(String imagePath, int width, int height) {
  161. return imagePath + "_" + width + "_" + height;
  162. }
  163.  
  164. /**
  165. * �?��ImageLoader
  166. *
  167. * */
  168. public void clear(){
  169. imageView2FileMap.clear();
  170. file2ImageViewMap.clear();
  171. fileInLoadSet.clear();
  172. for(String cacheKey : cacheKeys){
  173. cache.remove(cacheKey);
  174. }
  175. cacheKeys.clear();
  176. imageView2FileMap = null;
  177. file2ImageViewMap = null;
  178. fileInLoadSet = null;
  179. cacheKeys = null;
  180. downloader = null;
  181. cache = null;
  182. }
  183.  
  184. /**
  185. * ImageLoader.java退出时调用
  186. *
  187. * */
  188. public void destory() {
  189. clear();
  190. ImageCache.destroy();
  191. }
  192.  
  193. public interface ImageDownloader{
  194. public Bitmap download(String path,int width, int height);
  195. }
  196.  
  197. /**
  198. * 通过file2ImageViewMap获取filePath对应的所有imageView列表 同时删除被回收的imageView,
  199. *
  200. * @param filePathKey
  201. * @return
  202. */
  203. private ArrayList<ImageView> getImageViewListForKey(String filePathKey) {
  204. ArrayList<ImageView> imageViewArrayList = new ArrayList<ImageView>();
  205. HashSet<ImageViewReference> imageViewReferences = file2ImageViewMap.get(filePathKey);
  206. if(imageViewReferences == null){
  207. return null;
  208. }
  209. Iterator<ImageViewReference> it = imageViewReferences.iterator();
  210. while (it.hasNext()) {
  211. ImageViewReference reference = it.next();
  212. if (reference.get() != null) {
  213. imageViewArrayList.add(reference.get());
  214. } else {
  215. it.remove();
  216. }
  217. }
  218. return imageViewArrayList;
  219. }
  220.  
  221. /**
  222. * 获取指定的filePath对应的有效imageView的数据
  223. *
  224. * @param filePathKey
  225. * @return
  226. */
  227. private int getCountOfImageViewForKey(String filePathKey) {
  228. ArrayList<ImageView> imageViewArrayList = getImageViewListForKey(filePathKey);
  229. if(imageViewArrayList == null){
  230. return 0;
  231. }else{
  232. return imageViewArrayList.size();
  233. }
  234. }
  235.  
  236. private static class ImageCache extends LruCache<String, Bitmap> {
  237. private static final int cacheSize = 10 * 1024 * 1024;
  238. private static ImageCache instance = new ImageCache(cacheSize);
  239. public static ImageCache getInstance(){
  240. return instance;
  241. }
  242. private ImageCache(int maxSize) {
  243. super(maxSize);
  244. }
  245. @Override
  246. protected int sizeOf(String key, Bitmap value) {
  247. return value.getByteCount();
  248. }
  249. public static void destroy(){
  250. if(instance == null){
  251. return;
  252. }
  253. instance.evictAll();
  254. instance = null;
  255. }
  256. }
  257.  
  258. private static class ImageViewReference extends WeakReference<ImageView> {
  259. public ImageViewReference(ImageView r) {
  260. super(r);
  261. }
  262. @Override
  263. public boolean equals(Object o) {
  264. ImageViewReference other=(ImageViewReference)o;
  265. return this.get()==other.get();
  266. }
  267. @Override
  268. public int hashCode() {
  269. ImageView imageView = this.get();
  270. if(imageView != null){
  271. return imageView.hashCode();
  272. }
  273. return 0;
  274. }
  275. }
  276.  
  277. }

ImageUtil.java

  1. package com.eiice.httpuimagetils;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.math.BigDecimal;
  5.  
  6. import android.graphics.Bitmap;
  7. import android.graphics.BitmapFactory;
  8. import android.graphics.Matrix;
  9. import android.graphics.drawable.BitmapDrawable;
  10. import android.graphics.drawable.Drawable;
  11. import android.util.Log;
  12.  
  13. public class ImageUtil {
  14.  
  15. static final String TAG="ImageUtil";
  16.  
  17. public static Bitmap compressPic2Bitmap(String picfullname) {
  18. BitmapFactory.Options options = new BitmapFactory.Options();
  19. options.inJustDecodeBounds = true;
  20. Bitmap bitmap = BitmapFactory.decodeFile(picfullname, options); // 此时返回bm为空
  21. options.inJustDecodeBounds = false;
  22. int be = (int) (options.outHeight / (float) 200);
  23. if (be <= 0)
  24. be = 1;
  25. options.inSampleSize = be;
  26. bitmap = BitmapFactory.decodeFile(picfullname, options);
  27. return bitmap;
  28. }
  29.  
  30. public static Drawable bitmap2Drawable(Bitmap bm) {
  31. BitmapDrawable bd = new BitmapDrawable(bm);
  32. return bd;
  33. }
  34.  
  35. public static Drawable compressPic2Drawable(String picfullname) {
  36. return bitmap2Drawable(compressPic2Bitmap(picfullname));
  37. }
  38.  
  39. public static Bitmap compressPic2Bitmap(Bitmap bitmap, int width, int height, boolean isAdjust) {
  40. if (bitmap.getWidth() < width && bitmap.getHeight() < height) {
  41. return bitmap;
  42. }
  43. float sx = new BigDecimal(width).divide(new BigDecimal(bitmap.getWidth()), 4, BigDecimal.ROUND_DOWN)
  44. .floatValue();
  45. float sy = new BigDecimal(height).divide(new BigDecimal(bitmap.getHeight()), 4, BigDecimal.ROUND_DOWN)
  46. .floatValue();
  47. if (isAdjust) {
  48. sx = (sx < sy ? sx : sy);
  49. sy = sx;
  50. }
  51. Matrix matrix = new Matrix();
  52. matrix.postScale(sx, sy);
  53. return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  54. }
  55.  
  56. public static Drawable compressPic2Drawable(String picfullname, int width, int height) {
  57. // Bitmap bitmap = compressPic2Bitmap(picfullname);
  58. // bitmap = compressPic2Bitmap(bitmap, width, height, true);
  59.  
  60. Bitmap bitmap = compressBitmap(picfullname, width, height);
  61. return new BitmapDrawable(bitmap);
  62. }
  63.  
  64. public static Bitmap compressBitmap(String path, int sdwidth, int sdheight) {
  65. BitmapFactory.Options options = new BitmapFactory.Options();
  66. options.inJustDecodeBounds = true;
  67.  
  68. BitmapFactory.decodeFile(path, options);
  69. options.inSampleSize = calculateSampleSize(options, sdwidth, sdheight);
  70. options.inJustDecodeBounds = false;
  71. options.inDither = false;
  72. options.inPreferredConfig = Bitmap.Config.RGB_565;
  73. return BitmapFactory.decodeFile(path, options);
  74. }
  75.  
  76. public static int calculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
  77. final int height = options.outHeight;
  78. final int width = options.outWidth;
  79. int inSampleSize = 1;
  80. if (height > reqHeight || width > reqWidth) {
  81. final int heightRatio = Math.round((float) height / (float) reqHeight);
  82. final int widthRatio = Math.round((float) width / (float) reqWidth);
  83. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
  84. }
  85. return inSampleSize;
  86. }
  87. /**
  88. * 有损压缩图片
  89. * @param filePath
  90. * @return
  91. */
  92. public static byte[] compressBitmap(String filePath) {
  93. Bitmap sourceBmp=BitmapFactory.decodeFile(filePath);
  94. if(sourceBmp!=null)
  95. {
  96. Log.e(TAG, "原大小"+sourceBmp.getByteCount());
  97. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  98. sourceBmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
  99. sourceBmp.recycle();
  100. sourceBmp=null;
  101. //如果压缩后还大于10M,再压一次,这种情况一般不会出现
  102. if(baos.size()>10*1024*1024)
  103. {
  104. byte[] bytes=baos.toByteArray();
  105. Bitmap tempBmp=BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  106. baos.reset();
  107. tempBmp.compress(Bitmap.CompressFormat.JPEG, 30, baos);
  108. tempBmp.recycle();
  109. tempBmp=null;
  110. }
  111. byte[] bytes=baos.toByteArray();
  112. Log.e(TAG, "压缩后大小"+bytes.length);
  113. return bytes;
  114. }else{
  115. return null;
  116. }
  117. }
  118.  
  119. public static Bitmap bytes2Bimap(byte[] b) {
  120. if (b.length != 0) {
  121. return BitmapFactory.decodeByteArray(b, 0, b.length);
  122. } else {
  123. return null;
  124. }
  125. }
  126. }

测试代码:activity_main.xml

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6.  
  7. <ImageView
  8. android:id="@+id/imageview"
  9. android:layout_width="400dp"
  10. android:layout_height="400dp" />
  11.  
  12. <Button
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:onClick="show" />
  16.  
  17. </LinearLayout>

MainActivity.java

  1. package com.eiice.cn;
  2.  
  3. import android.app.Activity;
  4. import android.graphics.Bitmap;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.ImageView;
  8.  
  9. import com.eiice.httpuimagetils.HttpUtil;
  10. import com.eiice.httpuimagetils.ImageLoader;
  11. import com.eiice.httpuimagetils.ImageLoader.ImageDownloader;
  12.  
  13. public class MainActivity extends Activity {
  14. private ImageLoader imageLoader;
  15. private ImageView imageview;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. imageview = (ImageView) findViewById(R.id.imageview);
  21. imageLoader = new ImageLoader(new ImageDownloader(){
  22. @Override
  23. public Bitmap download(String path, int width, int height) {
  24. return HttpUtil.download(path);
  25. }
  26. });
  27. }
  28.  
  29. public void show(View view){
  30.  
  31. String imagepath = "http://img4.duitang.com/uploads/blog/201309/30/20130930115633_h8BEL.thumb.600_0.jpeg";
  32. imageLoader.loadImage(imagepath , 50, 50, imageview);
  33. }
  34.  
  35. @Override
  36. protected void onDestroy() {
  37. // TODO Auto-generated method stub
  38. super.onDestroy();
  39. imageLoader.destory();
  40. }
  41.  
  42. }

Android加载网络图片的工具类的更多相关文章

  1. android html 图片处理类--加载富文本工具类

    在android开发中,一些资讯类页面,里面有html标签和图片,html 标签一般通过Html.fromHtml方法,即可以解决,但是如果html 有图片标签,那么,Html.fromHtml 好像 ...

  2. Android加载网络图片报android.os.NetworkOnMainThreadException异常

    Android加载网络图片大致可以分为两种,低版本的和高版本的.低版本比如4.0一下或者更低版本的API直接利用Http就能实现了: 1.main.xml <?xml version=" ...

  3. Java加载Properties配置文件工具类

    Java加载Properties配置文件工具类 import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; ...

  4. Android加载网络图片学习过程

    好多应用,像我们公司的<乘友>还有其他的<飞鸽><陌陌><啪啪>这些,几乎每一款应用都需要加载网络图片,那ToYueXinShangWan,这是比须熟练 ...

  5. android 加载网络图片

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  6. Android 加载网络图片设置到ImageView

    下载图片后显示在ImageView中 //1.定义全局变量 private Handler handler; private String image_url; private Bitmap bitm ...

  7. 加载Properties文件工具类:LoadConfig

    import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; impor ...

  8. Android中用双缓存技术,加载网络图片

    最近在学校参加一个比赛,写的一个Android应用,里面要加载大量的网络图片,可是用传统的方法图片一多就会造成程序出现内存溢出而崩溃.因为自己也在学习中,所以看了很多博客和视频,然后参照这些大神的写源 ...

  9. Android Volley入门到精通:使用Volley加载网络图片

    在上一篇文章中,我们了解了Volley到底是什么,以及它的基本用法.本篇文章中我们即将学习关于Volley更加高级的用法,如何你还没有看过我的上一篇文章的话,建议先去阅读Android Volley完 ...

随机推荐

  1. 二模 (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 ...

  2. ros使用RPLIDAR激光雷达

    1.首先下载RPLIDAR的驱动功能包 https://github.com/robopeak/rplidar_ros 2.然后解压放到~/catkin_ws/src目录下 3.执行catkin_ma ...

  3. [开发笔记]-页面切图、CSS前端设计、JS

    这两天在学习页面的切图,样式设计,把学习过程中注意的地方记录下来. 一. input输入框点击时去掉外边框 一般在IE,firefox下,设置 border:0 none; 即可.但在chrome下, ...

  4. 【第41套测试题NOIP2007】【排序】【DP】【高精度】【树】【图上路径】

    先说点题外话,这两天的入学考试,炸了……语文有史以来最差,数学有史以来最差……还有4科,估计全炸……悲痛的心情,来调程序.这套题是8.31考的,从昨天晚上开始改的,因为第三题迟迟不想写,才拖到了现在. ...

  5. <转载>DB2常用命令

    1.数据库的启动.停止    db2start --启动   db2stop [force] --停止 2.与数据库的连接.断开   db2 CONNECT TO DBName [user UserI ...

  6. ModuleWorks免费下载使用方法大全

    ModuleWorks为模拟机器的工具运转及(或)机床和车床材料的搬运提供了一整套解决方案. 模拟技术可以识别潜在的碰撞问题,允许在NC代码生成前进行除错检查,并且渐渐成为CAM处理方面必不可少的解决 ...

  7. java基础之 创建对象的几种方式

    有4种显式地创建对象的方式: 1.用new语句创建对象,这是最常用的创建对象的方式. 2.运用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor ...

  8. Core Text概述

    本文是我翻译的苹果官方文档<Core Text Overview> Core Text框架是高级的底层文字布局和处理字体的技术.它在Mac OS X v10.5 and iOS 3.2开始 ...

  9. POJ 3156 - Interconnect (概率DP+hash)

    题意:给一个图,有些点之间已经连边,现在给每对点之间加边的概率是相同的,问使得整个图连通,加边条数的期望是多少. 此题可以用概率DP+并查集+hash来做. 用dp(i,j,k...)表示当前的每个联 ...

  10. How to Write Doc Comments for the Javadoc Tool

    http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html This document describe ...