【问题标题】:Android image fetching安卓图片抓取
【发布时间】:2011-02-23 22:55:36
【问题描述】:

从 android 程序中的 url 获取图像的最简单方法是什么?

【问题讨论】:

    标签: android


    【解决方案1】:

    我强烈建议改用AsyncTask。我最初使用URL.openStream,但它有issues

    class DownloadThread extends AsyncTask<URL,Integer,List<Bitmap>>{
     protected List<Bitmap> doInBackground(URL... urls){
      InputStream rawIn=null;
      BufferedInputStream bufIn=null;
      HttpURLConnection conn=null;
      try{
       List<Bitmap> out=new ArrayList<Bitmap>();
       for(int i=0;i<urls.length;i++){
        URL url=urls[i];
        url = new URL("http://mysite/myimage.png");
        conn=(HttpURLConnection) url.openConnection()
        if(!String.valueOf(conn.getResponseCode()).startsWith('2'))
          throw new IOException("Incorrect response code "+conn.getResponseCode()+" Message: " +getResponseMessage());
        rawIn=conn.getInputStream();
        bufIn=new BufferedInputStream();
        Bitmap b=BitmapFactory.decodeStream(in);
        out.add(b);
        publishProgress(i);//Remove this line if you don't want to use AsyncTask
      }
        return out;
      }catch(IOException e){
        Log.w("networking","Downloading image failed");//Log is an Android specific class
        return null;
      }
      finally{
       try {
         if(rawIn!=null)rawIn.close();
         if(bufIn!=null)bufIn.close();         
         if(conn!=null)conn.disconnect();
       }catch (IOException e) {
         Log.w("networking","Closing stream failed");
       }
      }
     }
    }
    

    在这种情况下,关闭流/连接和异常处理很困难。根据Sun Documentation,您应该只需要关闭最外面的流,但是it appears to be more complicated。但是,如果我们无法关闭BufferedInputStream,我将首先关闭最内部的流以确保它已关闭。

    我们在 finally 中关闭,以便异常不会阻止它们被关闭。如果异常阻止它们被初始化,我们会考虑流将是null 的可能性。如果我们在关闭期间出现异常,我们只需记录并忽略它。如果发生运行时错误,即使这样也可能无法正常工作。

    您可以按如下方式使用AsyncTask 类。在onPreExecute 中启动动画。更新onProgressUpdate中的进度。 onPostExecute 应该处理实际图像。使用onCancel 允许用户取消操作。以AsyncTask.execute 开头。

    值得注意的是,source code 和许可允许我们在非 Android 项目中使用该类。

    【讨论】:

      【解决方案2】:

      您可以通过多种方式做到这一点,但我能想到的最简单的方式是这样的:

      Bitmap IMG;
      Thread t = new Thread(){
          public void run(){
          try {
              /* Open a new URL and get the InputStream to load data from it. */ 
              URL aURL = new URL("YOUR URL"); 
          URLConnection conn = aURL.openConnection(); 
          conn.connect(); 
          InputStream is = conn.getInputStream(); 
          /* Buffered is always good for a performance plus. */ 
          BufferedInputStream bis = new BufferedInputStream(is); 
          /* Decode url-data to a bitmap. */ 
          IMG = BitmapFactory.decodeStream(bis);
          bis.close(); 
          is.close(); 
      
          // ...send message to handler to populate view.
          mHandler.sendEmptyMessage(0);
      
      } catch (Exception e) {
          Log.e(DEB, "Remtoe Image Exception", e);
      
          mHandler.sendEmptyMessage(1);
      } finally {
      }
      }
      };
      
      t.start();
      

      然后将处理程序添加到您的代码中:

          private Handler mHandler = new Handler(){
          public void handleMessage(Message msg) {
              switch(msg.what){
              case 0:
                  (YOUR IMAGE VIEW).setImageBitmap(IMG);
                  break;
              case 1:
                  onFail();
                  break;
              }
          }
      };
      

      通过启动一个线程并添加一个处理程序,您可以加载图像而无需在下载过程中锁定 UI。

      【讨论】:

      • 我实际上忘记在我的原始代码中关闭我的流。你真的应该在 finally 块中关闭你的流
      猜你喜欢
      • 1970-01-01
      • 2012-04-19
      • 2011-10-22
      • 2016-07-08
      • 2011-06-23
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多