Android异步加载网络图片

  1. Task task = (Task)msg.obj;

  2. // 调用callback对象的loadImage方法,并将图片路径和图片回传给adapter

  3. task.callback.loadImage(task.path, task.bitmap);

  4. }

  5. };

  6. private Runnable runnable = new Runnable() {

  7. @Override

  8. public void run() {

  9. while(isRunning){

  10. // 当队列中还有未处理的任务时,执行下载任务

  11. while(taskQueue.size() > 0){

  12. // 获取第一个任务,并将之从任务队列中删除

  13. Task task = taskQueue.remove(0);

  14. // 将下载的图片添加到缓存

  15. task.bitmap = PicUtil.getbitmap(task.path);

  16. caches.put(task.path, new SoftReference(task.bitmap));

  17. if(handler != null){

  18. // 创建消息对象,并将完成的任务添加到消息对象中

  19. Message msg = handler.obtainMessage();

  20. msg.obj = task;

  21. // 发送消息回主线程

  22. handler.sendMessage(msg);

  23. }

  24. }

  25. //如果队列为空,则令线程等待

  26. synchronized (this) {

  27. try {

  28. this.wait();

  29. } catch (InterruptedException e) {

  30. e.printStackTrace();

  31. }

  32. }

  33. }

  34. }

  35. };

  36. //回调接口

  37. public interface ImageCallback{

  38. void loadImage(String path, Bitmap bitmap);

  39. }

  40. class Task{

  41. // 下载任务的下载路径

  42. String path;

  43. // 下载的图片

  44. Bitmap bitmap;

  45. // 回调对象

  46. ImageCallback callback;

  47. @Override

  48. public boolean equals(Object o) {

  49. Task task = (Task)o;

  50. return task.path.equals(path);

  51. }

  52. }

  53. }

最后附上PicUtil类的代码,之前忘了贴这个类的代码,不好意识了~~

[java]  view plain copy

  1. public class PicUtil {

  2. private static final String TAG = “PicUtil”;

  3. /**

  4. * 根据一个网络连接(URL)获取bitmapDrawable图像

  5. *

  6. * @param imageUri

  7. * @return

  8. */

  9. public static BitmapDrawable getfriendicon(URL imageUri) {

  10. BitmapDrawable icon = null;

  11. try {

  12. HttpURLConnection hp = (HttpURLConnection) imageUri

  13. .openConnection();

  14. icon = new BitmapDrawable(hp.getInputStream());// 将输入流转换成bitmap

  15. hp.disconnect();// 关闭连接

  16. } catch (Exception e) {

  17. }

  18. return icon;

  19. }

  20. /**

  21. * 根据一个网络连接(String)获取bitmapDrawable图像

  22. *

  23. * @param imageUri

  24. * @return

  25. */

  26. public static BitmapDrawable getcontentPic(String imageUri) {

  27. URL imgUrl = null;

  28. try {

  29. imgUrl = new URL(imageUri);

  30. } catch (MalformedURLException e1) {

  31. e1.printStackTrace();

  32. }

  33. BitmapDrawable icon = null;

  34. try {

  35. HttpURLConnection hp = (HttpURLConnection) imgUrl.openConnection();

  36. icon = new BitmapDrawable(hp.getInputStream());// 将输入流转换成bitmap

  37. hp.disconnect();// 关闭连接

  38. } catch (Exception e) {

  39. }

  40. return icon;

  41. }

  42. /**

  43. * 根据一个网络连接(URL)获取bitmap图像

  44. *

  45. * @param imageUri

  46. * @return

  47. */

  48. public static Bitmap getusericon(URL imageUri) {

  49. // 显示网络上的图片

  50. URL myFileUrl = imageUri;

  51. Bitmap bitmap = null;

  52. try {

  53. HttpURLConnection conn = (HttpURLConnection) myFileUrl

  54. .openConnection();

  55. conn.setDoInput(true);

  56. conn.connect();

  57. InputStream is = conn.getInputStream();

  58. bitmap = BitmapFactory.decodeStream(is);

  59. is.close();

  60. } catch (IOException e) {

  61. e.printStackTrace();

  62. }

  63. return bitmap;

  64. }

  65. /**

  66. * 根据一个网络连接(String)获取bitmap图像

  67. *

  68. * @param imageUri

  69. * @return

  70. * @throws MalformedURLException

  71. */

  72. public static Bitmap getbitmap(String imageUri) {

  73. // 显示网络上的图片

  74. Bitmap bitmap = null;

  75. try {

  76. URL myFileUrl = new URL(imageUri);

  77. HttpURLConnection conn = (HttpURLConnection) myFileUrl

  78. .openConnection();

  79. conn.setDoInput(true);

  80. conn.connect();

  81. InputStream is = conn.getInputStream();

  82. bitmap = BitmapFactory.decodeStream(is);

  83. is.close();

  84. Log.i(TAG, “image download finished.” + imageUri);

  85. } catch (IOException e) {

  86. e.printStackTrace();

  87. return null;

  88. }

  89. return bitmap;

  90. }

  91. /**

  92. * 下载图片 同时写道本地缓存文件中

  93. *

  94. * @param context

  95. * @param imageUri

  96. * @return

  97. * @throws MalformedURLException

  98. */

  99. public static Bitmap getbitmapAndwrite(String imageUri) {

  100. Bitmap bitmap = null;

  101. try {

  102. // 显示网络上的图片

  103. URL myFileUrl = new URL(imageUri);

  104. HttpURLConnection conn = (HttpURLConnection) myFileUrl

  105. .openConnection();

  106. conn.setDoInput(true);

  107. conn.connect();

  108. InputStream is = conn.getInputStream();

  109. File cacheFile = FileUtil.getCacheFile(imageUri);

  110. BufferedOutputStream bos = null;

  111. bos = new BufferedOutputStream(new FileOutputStream(cacheFile));

  112. Log.i(TAG, "write file to " + cacheFile.getCanonicalPath());

  113. byte[] buf = new byte[1024];

  114. int len = 0;

  115. // 将网络上的图片存储到本地

  116. while ((len = is.read(buf)) > 0) {

  117. bos.write(buf, 0, len);

  118. }

  119. is.close();

  120. bos.close();

  121. // 从本地加载图片

  122. bitmap = BitmapFactory.decodeFile(cacheFile.getCanonicalPath());

  123. String name = MD5Util.MD5(imageUri);

  124. } catch (IOException e) {

  125. e.printStackTrace();

  126. }

  127. return bitmap;

  128. }

  129. public static boolean downpic(String picName, Bitmap bitmap) {

  130. boolean nowbol = false;

  131. try {

  132. File saveFile = new File(“/mnt/sdcard/download/weibopic/” + picName

  133. + “.png”);

  134. if (!saveFile.exists()) {

  135. saveFile.createNewFile();

  136. }

  137. FileOutputStream saveFileOutputStream;

  138. saveFileOutputStream = new FileOutputStream(saveFile);

  139. nowbol = bitmap.compress(Bitmap.CompressFormat.PNG, 100,

  140. saveFileOutputStream);

  141. saveFileOutputStream.close();

  142. } catch (FileNotFoundException e) {

  143. e.printStackTrace();

  144. } catch (IOException e) {

  145. e.printStackTrace();

  146. } catch (Exception e) {

  147. e.printStackTrace();

  148. }

  149. return nowbol;

  150. }

  151. public static void writeTofiles(Context context, Bitmap bitmap,

  152. String filename) {

  153. BufferedOutputStream outputStream = null;

  154. try {

  155. outputStream = new BufferedOutputStream(context.openFileOutput(

  156. filename, Context.MODE_PRIVATE));

  157. bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);

  158. } catch (FileNotFoundException e) {

  159. e.printStackTrace();

  160. }

  161. }

  162. /**

  163. * 将文件写入缓存系统中

  164. *

  165. * @param filename

  166. * @param is

  167. * @return

  168. */

  169. public static String writefile(Context context, String filename,

  170. InputStream is) {

  171. BufferedInputStream inputStream = null;

  172. BufferedOutputStream outputStream = null;

  173. try {

  174. inputStream = new BufferedInputStream(is);

  175. outputStream = new BufferedOutputStream(context.openFileOutput(

  176. filename, Context.MODE_PRIVATE));

  177. byte[] buffer = new byte[1024];

  178. int length;

  179. while ((length = inputStream.read(buffer)) != -1) {

  180. outputStream.write(buffer, 0, length);

  181. }

  182. } catch (Exception e) {

  183. } finally {

  184. if (inputStream != null) {

  185. try {

  186. inputStream.close();

  187. } catch (IOException e) {

  188. e.printStackTrace();

  189. }

  190. }

  191. if (outputStream != null) {

  192. try {

  193. outputStream.flush();

  194. outputStream.close();

  195. } catch (IOException e) {

  196. e.printStackTrace();

  197. }

  198. }

  199. }

  200. return context.getFilesDir() + “/” + filename + “.jpg”;

  201. }

  202. // 放大缩小图片

  203. public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {

  204. int width = bitmap.getWidth();

  205. int height = bitmap.getHeight();

  206. Matrix matrix = new Matrix();

  207. float scaleWidht = ((float) w / width);

  208. float scaleHeight = ((float) h / height);

  209. matrix.postScale(scaleWidht, scaleHeight);

  210. Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,

  211. matrix, true);

  212. return newbmp;

  213. }

  214. // 将Drawable转化为Bitmap

  215. public static Bitmap drawableToBitmap(Drawable drawable) {

  216. int width = drawable.getIntrinsicWidth();

  217. int height = drawable.getIntrinsicHeight();

  218. Bitmap bitmap = Bitmap.createBitmap(width, height, drawable

  219. .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

  220. : Bitmap.Config.RGB_565);

  221. Canvas canvas = new Canvas(bitmap);

  222. drawable.setBounds(0, 0, width, height);

  223. drawable.draw(canvas);

  224. return bitmap;

  225. }

  226. // 获得圆角图片的方法

  227. public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

  228. if(bitmap == null){

  229. return null;

  230. }

  231. Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),

  232. bitmap.getHeight(), Config.ARGB_8888);

  233. Canvas canvas = new Canvas(output);

  234. final int color = 0xff424242;

  235. final Paint paint = new Paint();

  236. final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

  237. final RectF rectF = new RectF(rect);

  238. paint.setAntiAlias(true);

  239. canvas.drawARGB(0, 0, 0, 0);

  240. paint.setColor(color);

  241. canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

  242. paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

  243. canvas.drawBitmap(bitmap, rect, rect, paint);

  244. return output;

  245. }

  246. // 获得带倒影的图片方法

  247. public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {

  248. final int reflectionGap = 4;

  249. int width = bitmap.getWidth();

  250. int height = bitmap.getHeight();

  251. Matrix matrix = new Matrix();

  252. matrix.preScale(1, -1);

  253. Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,

  254. width, height / 2, matrix, false);

  255. Bitmap bitmapWithReflection = Bitmap.createBitmap(width,

  256. (height + height / 2), Config.ARGB_8888);

  257. Canvas canvas = new Canvas(bitmapWithReflection);

  258. canvas.drawBitmap(bitmap, 0, 0, null);

  259. Paint deafalutPaint = new Paint();

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

总结

最后对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上上述的技术体系图相关的几十套腾讯、头条、阿里、美团等公司20年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

相信它会给大家带来很多收获:

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!

以上Android开发知识点,真正体系化!**

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

总结

最后对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上上述的技术体系图相关的几十套腾讯、头条、阿里、美团等公司20年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

相信它会给大家带来很多收获:
[外链图片转存中…(img-CKgrlr9m-1712228623819)]

[外链图片转存中…(img-mVh9HWTv-1712228623820)]

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
  • 16
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值