Android学习之BitMap用法实例
下面简单说明了BitMap的用法:
从服务器下载一张图片,显示在ImageView控件上,并将该图片保存在移动设备的SD上。
1 // 根据网络URL获取输入流 2 public InputStream getUrlInputStream(String strUrl) throws IOException { 3 URL url = new URL(strUrl); 4 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 5 InputStream inputStream = conn.getInputStream(); 6 if (inputStream != null) { 7 return inputStream; 8 } else { 9 Log.i("inputStream", "输入流对象为空"); 10 return null; 11 } 12 } 13 14 // 将输入流转化为Bitmap流 15 public Bitmap getBitmap(InputStream inputStream) { 16 Bitmap bitmap = null; 17 if (inputStream != null) { 18 bitmap = BitmapFactory.decodeStream(inputStream); 19 return bitmap; 20 } else { 21 Log.i("test", "输入流对象in为空"); 22 return null; 23 } 24 } 25 26 // 给ImageView对象赋值 27 public void setWidgetImage(Bitmap bitmap) { 28 ImageView img = new ImageView(this); 29 if (bitmap != null) { 30 img.setImageBitmap(bitmap); 31 } 32 } 33 34 // 获取SD卡上的文件存储路径 35 public void createSDFile() { 36 File sdroot = Environment.getExternalStorageDirectory(); 37 File file = new File(sdroot + "/Android/date/包名/文件名"); 38 if (Environment.MEDIA_MOUNTED.equals(Environment 39 .getExternalStorageState())) { 40 // 相关操作 41 } 42 } 43 44 // 将图片保存到SD卡上 45 public boolean readToSDCard(File file, Bitmap bitmap) 46 throws FileNotFoundException { 47 FileOutputStream os = new FileOutputStream(file); 48 return bitmap.compress(Bitmap.CompressFormat.PNG, 90, os); 49 // true:表示操作成功,false:表示操作失败 50 }