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     }
相關文章
相關標籤/搜索