Android通過url獲取bitmap圖片問題

  1. //定義一個根據圖片url獲取InputStream的方法  
  2.     public static byte[] getBytes(InputStream is) throws IOException {  
  3.         ByteArrayOutputStream outstream = new ByteArrayOutputStream();  
  4.         byte[] buffer = new byte[1024]; // 用數據裝  
  5.         int len = -1;  
  6.         while ((len = is.read(buffer)) != -1) {  
  7.             outstream.write(buffer, 0, len);  
  8.         }  
  9.         outstream.close();  
  10.         // 關閉流一定要記得。  
  11.         return outstream.toByteArray();  
  12.     }  
  13.   
  14. //然後使用方法decodeByteArray()方法解析編碼,生成Bitmap對象。  
  15.     byte[] data = getBytes(new URL(imgUrl).openStream());  
  16.     Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);  
以下是一個設置壁紙的實例應用
	new Thread(){
				@Override
				public void run(){
					//你要執行的方法
					try {
						byte[] data = getBytes(new URL(picurl).openStream());  
						bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
						WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
						wallpaperManager.setBitmap(bitmap);
					}
					catch (Exception e) {
						Toast.makeText(DialogPhotoEntry.this,"設置桌面圖片失敗", 1000).show();
						e.printStackTrace();
					}
					//執行完畢後給handler發送一個空消息
					handler.sendEmptyMessage(0);
				}
			}.start();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章