Set Image to a ImageView from URL [duplicate]

余生颓废 提交于 2020-01-01 19:29:10

问题


I have Imageview and a link to the picture on the Internet. I set this picture to the ImageView like this,

public ImageView iv;
iv = (ImageView) findViewById(R.id.imageView);
String img = "https://www.google.com/images/srpr/logo11w.png";
iv.setImageDrawable(Drawable.createFromPath(img));

What I want to do is download a picture from the internet to my android application and apply it to an ImageView. I want to make it as easy as possible.

helped me

String img_url= //url of the image
    URL url=new URL(img_url);
    Bitmap bmp; 
    bmp=BitmapFactory.decodeStream(url.openConnection().getInputStream());
    ImageView iv=(ImageView)findviewById(R.id.imageview);
    iv.setImageBitmap(bmp);

回答1:


There many libs to do this, my favourite is Picasso.

Here an example of usage:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

give it a try :)




回答2:


This method create a Drawable from file path name. Check this answer.




回答3:


There are many libraries available on doing this, I recommend using a library, because a they have many extra options availble.

Take Universal Image Loader

Features

  • Multithread image loading
  • Possibility of wide tuning ImageLoader's configuration (thread executors, downloader, decoder, memory and disc cache, display image options, and others)
  • Possibility of image caching in memory and/or on device's file system (or SD card)
  • Possibility to "listen" loading process
  • Possibility to customize every display image call with separated options Widget support
  • Possibility to show an custom Image on loading, error, etc.

You have to set the options one time using:

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions)
            .build();
ImageLoader.getInstance().init(config);

Then, lateron you can use this anywhere in your code:

ImageView iv = (ImageView) findViewById(R.id.imageView);
String str = "http://google.com/img.jpg";

ImageLoader.getInstance().displayImage(str, iv);

Ofcourse there are many other libraries you can use like picasso, Smart Image View, Url Image View and many others.



来源:https://stackoverflow.com/questions/22008754/set-image-to-a-imageview-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!