【问题标题】:Image from Url in Android图片来自 Android 中的 Url
【发布时间】:2013-10-29 06:34:11
【问题描述】:

我正在尝试从我正在使用的 Web 服务设置图像:

private class FetchImageTask extends AsyncTask<String, Integer, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... arg0) {
        Bitmap b = null;
        try {
            b = BitmapFactory.decodeStream((InputStream) new URL(arg0[0]).getContent());
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }
}

并尝试像这样获取它

final ImageView imgicon = (ImageView) convertView.findViewById(R.id.imgicon); 
    new FetchImageTask() {
        @Override
        protected void onPostExecute(Bitmap result) {

            if (result != null) {
                imgicon.setImageBitmap(result);

            }
        }
    }.execute("Url/images/"+bitmapname);

但它既不显示也不显示任何错误。有什么猜测吗?

【问题讨论】:

    标签: android


    【解决方案1】:

    来自 Android 开发者博客

    使用此异步任务

    class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    private String url;
    private final WeakReference<ImageView> imageViewReference;
    
    public BitmapDownloaderTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }
    
    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
         // params comes from the execute() call: params[0] is the url.
         return downloadBitmap(params[0]);
    }
    
    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }
    
        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
    }
    

    使用此功能从 url 下载位图

    static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);
    
    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) { 
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
            return null;
        }
    
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent(); 
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();  
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        // Could provide a more explicit error message for IOException or IllegalStateException
        getRequest.abort();
        Log.w("ImageDownloader", "Error while retrieving bitmap from " + url, e.toString());
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
    }
    

    如下调用asynctask

    ImageView mImageView = (ImageView)findViewById(yourImageViewId);
    BitmapDownloaderTask mDownloaderTask = new BitmapDownloaderTask(mImageView);
    mDownloaderTask.execute("YourDownloadUrlHere");
    

    【讨论】:

      【解决方案2】:

      试试这个:

      public Bitmap getBitmapFromURL(String src) {
          try {
              java.net.URL url = new java.net.URL(src);
              HttpURLConnection connection = (HttpURLConnection) url
                      .openConnection();
              connection.setDoInput(true);
              connection.connect();
              InputStream input = connection.getInputStream();
              Bitmap myBitmap = BitmapFactory.decodeStream(input);
              return myBitmap;
          } catch (IOException e) {
              e.printStackTrace();
              return null;
          }
      }
      

      对于 OutOfMemoryIssue 使用:

      public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
          int width = bm.getWidth();
          int height = bm.getHeight();
          float scaleWidth = ((float) newWidth) / width;
          float scaleHeight = ((float) newHeight) / height;
          // CREATE A MATRIX FOR THE MANIPULATION
          Matrix matrix = new Matrix();
          // RESIZE THE BIT MAP
          matrix.postScale(scaleWidth, scaleHeight);
      
          // "RECREATE" THE NEW BITMAP
          Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
                  matrix, false);
      
          return resizedBitmap;
      }
      

      【讨论】:

        【解决方案3】:

        做这样的事情:

        private class FetchImageTask extends AsyncTask<String, Integer, Bitmap> {
            @Override
            protected Bitmap doInBackground(String... arg0) {
                Bitmap b = null;
                try {
                    b = BitmapFactory.decodeStream((InputStream) new URL(arg0[0]).getContent());
                }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                return b;
            }
            @Override
            protected void onPostExecute(Bitmap result) {
        
                if (result != null) {
                    imgicon.setImageBitmap(result);
        
                }
            }
        }
        

        然后这样称呼它:

        final ImageView imgicon = (ImageView) convertView.findViewById(R.id.imgicon); 
        new FetchImageTask().execute("Url/images/"+bitmapname);
        

        【讨论】:

          【解决方案4】:
          private class FetchImageTask extends AsyncTask<String, Integer, Bitmap> {
              @Override
              protected void doInBackground(String... arg0) {
                  try {
                  java.net.URL url = new java.net.URL(arg0[0]);
                  HttpURLConnection connection = (HttpURLConnection) url
                          .openConnection();
                  connection.setDoInput(true);
                  connection.connect();
                  InputStream input = connection.getInputStream();
                  Bitmap myBitmap = BitmapFactory.decodeStream(input);
          
              } catch (IOException e) {
                  e.printStackTrace();
                  return null;
              }
                  return null;
              }
          }
          @Override
              protected void onPostExecute(Bitmap result) {
          
          
                      imageview.setImageBitmap(mybitmap);
          
                  }
              }
          

          【讨论】:

            【解决方案5】:
            1. Download the AndroidQuery jar.

            2. 将此 jar 放入您的 libs 文件夹并右键单击 jar 并 构建路径 -> 添加到构建路径

            根据此示例使用它:

            AQuery androidQuery = new AQuery(this); // make AndroidQuery object
            
            androidQuery
                .id(yourImageView)
                .image(
                    imageUrl,
                    isCacheUrlImageOnMemery, 
                    isCacheUrlImageOnFile);
            

            如果为 true,则在内存中给出 URL 图像缓存,因此在 word android 查询检查后,在内存或文件中给出 URL 图像缓存,然后它从缓存中获取,否则它会尝试从 URL 获取

            isCacheUrlImageOnMemery
            

            isCacheUrlImageOnMemery 相同,但首先 android 查询检查内存然后文件,以防我们没有太多内存,然后我们缓存在文件中,这两个选项都可用。

            isCacheUrlImageOnFile
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-09-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-03-26
              • 2012-08-23
              • 1970-01-01
              • 2021-08-24
              相关资源
              最近更新 更多