异步获取网络图片Bitmap
来源:互联网 发布:淘宝代做毕业设计真假 编辑:程序博客网 时间:2024/05/01 06:02
从网路获取图片,使用AsyncTask异步通信。
异步代码如下:
public void addTask(String url) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { // 后台通信 return decodeBitmap(params[0]);// return byteBitmap(params[0]); } @Override protected void onPostExecute(Bitmap bitmap) { // 主线程处理view if (bitmap != null) { mTestImage.setImageBitmap(bitmap); } } }.execute(url); }
后台处理方法
方法一:使用 BitmapdecodeStream(InputStream is)
private Bitmap decodeBitmap(String httpUrl) { URL url = null; Bitmap bm = null; try { url = new URL(httpUrl); } catch (MalformedURLException e) { e.printStackTrace(); } try { InputStream in = url.openStream(); bm = BitmapFactory.decodeStream(in); } catch (IOException e) { e.printStackTrace(); } return bm; }
方法二:使用BitmapFactory.decodeByteArray(data,0,data.length)
private Bitmap byteBitmap(String httpUrl) { Bitmap bitmap = null; try { HttpURLConnection connection = (HttpURLConnection)(new URL(httpUrl)).openConnection(); connection.setDoInput(true); connection.connect(); InputStream is = connection.getInputStream(); try { byte[] data = readStream(is); if(data != null){ bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (Exception e) { e.printStackTrace(); } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } return bitmap; } public static byte[] readStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len=inStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); } outStream.close(); inStream.close(); return outStream.toByteArray(); }
1 0
- 异步获取网络图片Bitmap
- Android 异步获取网络图片Bitmap资源
- bitmap 获取网络图片
- Bitmap异步加载网络图片
- 根据图片的网络URL获取Bitmap
- 异步加载bitmap图片
- Bitmap 图片异步加载
- Android ListView异步获取网络图片
- Android异步加载获取网络数据(图片)
- 关于异步加载获取网络图片的
- 通过AsyncTask异步获取网络图片
- 从网络获取图片直接存为bitmap
- 获取网络图片(Bitmap)至内存或者SD卡
- android从网络获取图片直接存为bitmap
- 网络图片url->bitmap
- android从网络获取图片以及异步加载图片
- android从网络获取图片以及异步加载图片
- android从网络获取图片以及异步加载图片
- js,二进制浮点数和四舍五入的问题
- 万能存储工具类SDCard存储 /data/data/存储 assets存储 raw存储
- PyQt给QLabel添加双击事件
- unity3d newline in constant error
- 《C#入门经典》第1章-第7章要点
- 异步获取网络图片Bitmap
- 软件工程基础知识----软件概述
- 玩转Google开源C++单元测试框架Google Test系列(gtest)之一 - 初始gtest
- 关于CString(互动百科)
- android异步任务详解 AsynTask
- Android权限Uri.parse的几种用法
- xcode 6 添加pch文件
- OC基础回顾(十二)协议
- FTPClient上传文件乱码