代码之家  ›  专栏  ›  技术社区  ›  Shanto George

从自动下载url加载图像

  •  1
  • Shanto George  · 技术社区  · 7 年前

    调用我的url时,它会自动从服务器下载图像。我需要在Android的ImageView上显示这个图像。我通常用 Piccaso 库从url加载图像,但这对我没有帮助,有没有办法从自动下载url加载图像到Android ImageView?

    自动下载url示例位于 here (wallpaperswide.com/download/bike_chase-wallpaper-2560x1600.jpg)

    1 回复  |  直到 7 年前
        1
  •  0
  •   Paraskevas Ntsounos Charith Lakshitha    7 年前

    好吧,如果不想使用像Piccaso这样的库,试试这样的方法:

    public class AsyncTaskLoadImage  extends AsyncTask<String, String, Bitmap> {
        private final static String TAG = "AsyncLoadImage"; 
        private ImageView imageView;
        public AsyncTaskLoadImage(ImageView imageView) {
        this.imageView = imageView;
        }
        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {
                URL url = new URL(params[0]);
                    bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap bitmap) {
           StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
           StrictMode.setThreadPolicy(policy);              
           imageView.setImageBitmap(bitmap);
        }
    }
    

    你的活动是这样的:

    String url = "YOUR_LINK_HERE";
    new AsyncTaskLoadImage(imageView).execute(url);
    

    或者

    用更少的代码尝试一些东西 like this answer :

    URL url = new URL("YOUR_LINK_HERE");
    Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    imageView.setImageBitmap(bmp);