2012-11-02 51 views
1

我正在瀏覽developer.android頁面以便高效地加載位圖,並且在這裏:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html他們討論將縮小版本加載到內存中,這顯然非常有效。有效地加載位圖

現在我的問題是,給定的方法需要資源的ID,我們沒有得到(請糾正我,如果我在這裏錯了),而從互聯網上下載圖像/位圖。

那麼,有什麼辦法可以使用給定的方法從互聯網下載的圖像的一些變化?

+1

'BitmapFactory方法。 decodeFile()'適用於圖像的文件路徑。 –

+0

謝謝,這正是我想要的! –

回答

0

哎,我不知道這個方法,但是這是我從互聯網上下載圖片,並保存到SD卡,你可以使用這個按您的要求我使用保存照片的保存

public class fetchImage extends Activity implements OnClickListener { 
    int id; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     id = 1;// declaring static as of now 

    } 

    { 

     new BackgroundTask().execute(); 
     File storagePath = Environment.getExternalStorageDirectory(); 
     File imgFile = new File(storagePath, "/Pictures/" + id + ".jpg"); 

     if (imgFile.exists()) { 
      Bitmap myBitmap = BitmapFactory.decodeFile(imgFile 
        .getAbsolutePath()); 
     } 

    } 

    class BackgroundTask extends AsyncTask<Void, Void, Void> { 
     ProgressDialog mDialog; 

     protected void onPreExecute() { 
      mDialog = ProgressDialog.show(fetchImage.this, "", 
        getString(R.string.progress_bar_loading), true); 
     }; 

     @Override 
     protected Void doInBackground(Void... params) { 
      try { 

       savesd(id, null); 

      } catch (final Exception e) { 

      } 
      return null; 
     } 

     private void savesd(int id, URL uri) throws IOException { 
      URL url; 
      if (uri == null) { 
       url = new URL("http://i.zdnet.com/blogs/3-29-androids.jpg"); 
      } else { 
       url = uri; 
      } 
      InputStream input = url.openStream(); 
      try { 
       File storagePath = Environment.getExternalStorageDirectory(); 
       OutputStream output = new FileOutputStream(new File(
         storagePath, "/Pictures/" + id + ".jpg")); 
       try { 
        byte[] buffer = new byte[20000]; 
        int bytesRead = 0; 
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
         output.write(buffer, 0, bytesRead); 
        } 
       } finally { 
        output.close(); 
       } 
      } catch (Exception e) { 

       e.printStackTrace(); 
      } finally { 
       input.close(); 
      } 

     } 

     protected void onPostExecute(Void result) { 
      mDialog.dismiss(); 
     }; 
    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

    } 

} 
相關問題