如何在Android中通过URL加载ImageView?

问题描述:

如何在ImageView中使用URL引用的图片?如何在Android中通过URL加载ImageView?

+1

试试这一个http://stackoverflow.com/questions/14332296/how-to-set图片来自网址使用asynctask/15797963#15797963 – comeGetSome 2013-04-07 16:27:17

+1

使用毕加索... http://stackoverflow.com/a/23865531/3535286 – chiragkyada 2014-05-26 08:12:47

+0

使用Glide http://www.gadgetsaint.com /android/circular-images-glide-library-android/#.WEj42rJ96Hs – ASP 2016-12-08 06:10:37

无论如何,人们会问我的意见,并将其发布为答案。我张贴。

URL newurl = new URL(photo_url_str); 
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); 
profile_photo.setImageBitmap(mIcon_val); 

谢谢。

+0

这是短而伟大的,谢谢 – Nactus 2014-05-01 19:29:35

+14

mm ..这不能从UI线程完成。 – Guy 2014-07-11 07:57:02

+2

对于有“格式不正确的URL执行”问题的人,请在try/catch中围绕上面的代码行。 http://stackoverflow.com/a/24418607/2093088 – 2015-06-23 16:28:37

你必须下载图像首先

public static Bitmap loadBitmap(String url) { 
    Bitmap bitmap = null; 
    InputStream in = null; 
    BufferedOutputStream out = null; 

    try { 
     in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); 

     final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 
     out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); 
     copy(in, out); 
     out.flush(); 

     final byte[] data = dataStream.toByteArray(); 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     //options.inSampleSize = 1; 

     bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options); 
    } catch (IOException e) { 
     Log.e(TAG, "Could not load Bitmap from: " + url); 
    } finally { 
     closeStream(in); 
     closeStream(out); 
    } 

    return bitmap; 
} 

然后使用Imageview.setImageBitmap设置位图到ImageView的

+124

你说得对。但只有这三条线有助于解决问题。 URL newurl = new URL(photo_url_str); mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() \t \t \t \t \t .getInputStream()); profile_photo.setImageBitmap(mIcon_val);感谢你的回复。 – Praveen 2010-03-19 08:57:04

+2

对于URL - 导入java.net.URL; private static final int IO_BUFFER_SIZE = 4 * 1024; 最后一个是什么? – Steve 2010-03-19 12:07:29

+12

看到这里的代码:http://stackoverflow.com/questions/3118691/android-make-an-image-at-a-url-equal-to-imageviews-image – OneWorld 2010-09-24 08:36:10

你也可以使用此LoadingImageView视图从URL中加载图像:

http://blog.blundellapps.com/imageview-with-loading-spinner/

一旦你添加了从该链接可以实例化一个URL图像视图类文件:

在XML:

<com.blundell.tut.LoaderImageView 
    android:id="@+id/loaderImageView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    image="http://developer.android.com/images/dialog_buttons.png" 
/> 

在代码:使用

final LoaderImageView image = new LoaderImageView(this, "http://developer.android.com/images/dialog_buttons.png"); 

和更新:

image.setImageDrawable("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"); 
+0

不错的示例,但我不认为这是线程安全的。我正在尝试在Async onPostExecute中使用它,但是onPostExecute有时可能会在回调接收到渲染空图像之前结束。 – Jimmy 2012-01-21 03:34:57

+0

这管理着它自己的线程。那么为什么不在你的ASyncTask完成后用你想要的url调用回UI。这样你就没有线程产生线程。 – Blundell 2012-08-11 11:19:26

public class LoadWebImg extends Activity { 

String image_URL= 
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     ImageView bmImage = (ImageView)findViewById(R.id.image); 
    BitmapFactory.Options bmOptions; 
    bmOptions = new BitmapFactory.Options(); 
    bmOptions.inSampleSize = 1; 
    Bitmap bm = LoadImage(image_URL, bmOptions); 
    bmImage.setImageBitmap(bm); 
    } 

    private Bitmap LoadImage(String URL, BitmapFactory.Options options) 
    {  
    Bitmap bitmap = null; 
    InputStream in = null;  
     try { 
      in = OpenHttpConnection(URL); 
      bitmap = BitmapFactory.decodeStream(in, null, options); 
      in.close(); 
     } catch (IOException e1) { 
     } 
     return bitmap;    
    } 

private InputStream OpenHttpConnection(String strURL) throws IOException{ 
InputStream inputStream = null; 
URL url = new URL(strURL); 
URLConnection conn = url.openConnection(); 

try{ 
    HttpURLConnection httpConn = (HttpURLConnection)conn; 
    httpConn.setRequestMethod("GET"); 
    httpConn.connect(); 

    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
    inputStream = httpConn.getInputStream(); 
    } 
} 
catch (Exception ex) 
{ 
} 
return inputStream; 
} 
} 
+0

非常感谢,我一直在寻找的完美例子................, 但错误主题这应该在这里==> [如何设置imageView的图像从一个字符串?](http://stackoverflow.com/questions/5254100/how-to-set-an-imageviews-image-from-a-string) – VenomVendor 2012-01-14 17:52:21

我写了一个类来处理这个问题,因为它似乎在我的各种项目中经常需要:

https://github.com/koush/UrlImageViewHelper

UrlImageViewHelper将填补 ImageView的与搜索 在URL的图像。

该示例将执行Google Image 异步搜索并加载/显示结果 。

UrlImageViewHelper将自动下载,保存并缓存所有的 图片,并将其映射到BitmapDrawables。 重复的网址不会被加载到 内存两次。通过使用弱基准散列表 来管理位图存储器 ,因此只要图像不再使用 ,它就会自动收集垃圾 。

+0

这是什么牌子,顺便说一下? – 2012-04-13 17:21:15

+0

@Shurane - Apache。我会在稍后记下它。 – koush 2012-04-16 17:48:25

+1

看来我们需要使用这个,而不是https://github.com/koush/ion,因为UrlImageViewHelper已被弃用,如在github项目的页面上显示的https://github.com/koush/UrlImageViewHelper。 – 2015-01-12 15:34:08

我最近发现一个线程here,因为我必须做类似的事情与图像的列表视图,但原理很简单,你可以在那里所示(由jleedev)第一样品课堂上阅读。 你获得图像的输入流(来自网络)

private InputStream fetch(String urlString) throws MalformedURLException, IOException { 
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    HttpGet request = new HttpGet(urlString); 
    HttpResponse response = httpClient.execute(request); 
    return response.getEntity().getContent(); 
} 

然后您存储图像绘制对象,你可以将它传递给ImageView的(通过setImageDrawable)。再次从上面的代码片段看看整个线程。

InputStream is = fetch(urlString); 
Drawable drawable = Drawable.createFromStream(is, "src"); 
+0

我的项目中没有DefaultHttpClient。 – 2015-11-28 08:16:34

您好我有最简单的代码试试这个

public class ImageFromUrlExample extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      ImageView imgView =(ImageView)findViewById(R.id.ImageView01); 
      Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png"); 
      imgView.setImageDrawable(drawable); 

    } 

    private Drawable LoadImageFromWebOperations(String url) 
    { 
      try{ 
     InputStream is = (InputStream) new URL(url).getContent(); 
     Drawable d = Drawable.createFromStream(is, "src name"); 
     return d; 
     }catch (Exception e) { 
     System.out.println("Exc="+e); 
     return null; 
     } 
    } 
    } 

为主。XML

<LinearLayout 
    android:id="@+id/LinearLayout01" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
    <ImageView 
     android:id="@+id/ImageView01" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content"/> 

试试这个

imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside 

private Bitmap getImageBitmap(String url) { 
     Bitmap bm = null; 
     try { 
      URL aURL = new URL(url); 
      URLConnection conn = aURL.openConnection(); 
      conn.connect(); 
      InputStream is = conn.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      bm = BitmapFactory.decodeStream(bis); 
      bis.close(); 
      is.close(); 
     } catch (IOException e) { 
      Log.e(TAG, "Error getting bitmap", e); 
     } 
     return bm; 
    } 

Android developer

// show The Image in a ImageView 
new DownloadImageTask((ImageView) findViewById(R.id.imageView1)) 
      .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"); 

public void onClick(View v) { 
    startActivity(new Intent(this, IndexActivity.class)); 
    finish(); 

} 

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { 
    ImageView bmImage; 

    public DownloadImageTask(ImageView bmImage) { 
     this.bmImage = bmImage; 
    } 

    protected Bitmap doInBackground(String... urls) { 
     String urldisplay = urls[0]; 
     Bitmap mIcon11 = null; 
     try { 
      InputStream in = new java.net.URL(urldisplay).openStream(); 
      mIcon11 = BitmapFactory.decodeStream(in); 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return mIcon11; 
    } 

    protected void onPostExecute(Bitmap result) { 
     bmImage.setImageBitmap(result); 
    } 
} 

确保您已在AndroidManifest.xml设置以下的权限来访问ŧ他互联网。

<uses-permission android:name="android.permission.INTERNET" /> 
+36

这太棒了。名单上应该更高。 asynctask允许加载而不会冻结UI! – 2012-06-03 05:26:12

+0

高效,它的作品完美 – jlopez 2012-08-27 08:34:48

+7

这应该是TOP答案! – Shehaaz 2013-04-06 00:21:23

一个简单和干净的方式做,这是使用开源库Prime

如果您是通过单击按钮加载图像,上述接受的答案是非常好的,但是如果您在新活动中进行加载,则会冻结UI一两秒。环顾四周,我发现一个简单的asynctask消除了这个问题。

要使用的AsyncTask在你活动的末尾添加这个类:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { 
    ImageView bmImage; 

    public DownloadImageTask(ImageView bmImage) { 
     this.bmImage = bmImage; 
    } 

    protected Bitmap doInBackground(String... urls) { 
     String urldisplay = urls[0]; 
     Bitmap mIcon11 = null; 
     try { 
      InputStream in = new java.net.URL(urldisplay).openStream(); 
      mIcon11 = BitmapFactory.decodeStream(in); 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return mIcon11; 
    } 

    protected void onPostExecute(Bitmap result) { 
     bmImage.setImageBitmap(result); 
    }  
} 

并使用来自您的onCreate()方法调用:

new DownloadImageTask((ImageView) findViewById(R.id.imageView1)) 
     .execute(MY_URL_STRING); 

结果是一个快速加载活动,根据用户的网络速度,稍后显示一秒的图像视图。

+0

这是快速和紧凑。很好地满足了我的需求!谢谢! – 2013-01-17 01:25:07

+0

真棒@凯尔。我喜欢你的榜样。 – 2013-05-28 05:13:20

+0

太棒了。谢谢!!!! – 2013-08-16 00:53:37

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); 

此代码已经过测试,它完全正常工作。

URL req = new URL(
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png" 
); 
Bitmap mIcon_val = BitmapFactory.decodeStream(req.openConnection() 
        .getInputStream()); 

很多很好的信息在这里......我最近发现了一个名为SmartImageView的类,它似乎目前工作得很好。非常容易并入和使用。

http://loopj.com/android-smart-image-view/

https://github.com/loopj/android-smart-image-view

更新:我最后写一个blog post about this,所以检查它使用SmartImageView帮助。

2ND UPDATE:我现在总是使用毕加索(见上),并强烈推荐它。 :)

这是一个较晚的答复,如上面建议AsyncTask将会和谷歌搜索后有点我找到了一个更多的方式来解决这个问题。

my_image_view.setImageDrawable(Drawable.createFromStream((InputStream)new 
URL(<String_url>).getContent(), "src")); 

我自己试过,我还没有面对任何问题。

+0

这实际上是非常好的极简主义!请记住,由于UI线程不允许网络操作,因此需要在额外的'Thread'中运行。 – creativecreatorormaybenot 2018-03-08 13:02:31

这将帮助你......

定义的ImageView和加载图像到它.....

Imageview i = (ImageView) vv.findViewById(R.id.img_country); 
i.setImageBitmap(DownloadFullFromUrl(url)); 

然后定义这个方法:

public Bitmap DownloadFullFromUrl(String imageFullURL) { 
    Bitmap bm = null; 
    try { 
     URL url = new URL(imageFullURL); 
     URLConnection ucon = url.openConnection(); 
     InputStream is = ucon.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 
     ByteArrayBuffer baf = new ByteArrayBuffer(50); 
     int current = 0; 
     while ((current = bis.read()) != -1) { 
      baf.append((byte) current); 
     } 
     bm = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, 
       baf.toByteArray().length); 
    } catch (IOException e) { 
     Log.d("ImageManager", "Error: " + e); 
    } 
    return bm; 
} 

Android的查询可以处理为你和更多(如缓存和加载进度)。

看看here

我认为是最好的方法。

任何容器中工作ImageView的,像列表视图网格视图,正常布局

private class LoadImagefromUrl extends AsyncTask< Object, Void, Bitmap > { 
     ImageView ivPreview = null; 

     @Override 
     protected Bitmap doInBackground(Object... params) { 
      this.ivPreview = (ImageView) params[0]; 
      String url = (String) params[1]; 
      System.out.println(url); 
      return loadBitmap(url); 
     } 

     @Override 
     protected void onPostExecute(Bitmap result) { 
      super.onPostExecute(result); 
      ivPreview.setImageBitmap(result); 
     } 
    } 

    public Bitmap loadBitmap(String url) { 
     URL newurl = null; 
     Bitmap bitmap = null; 
     try { 
      newurl = new URL(url); 
      bitmap = BitmapFactory.decodeStream(newurl.openConnection().getInputStream()); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 
     return bitmap; 
    } 
/** Usage **/ 
    new LoadImagefromUrl().execute(imageView, url); 
+0

+1感谢您提供完整,简单的解决方案。 – PeteH 2014-03-02 21:00:05

版本与异常处理和异步任务:

AsyncTask<URL, Void, Boolean> asyncTask = new AsyncTask<URL, Void, Boolean>() { 
    public Bitmap mIcon_val; 
    public IOException error; 

    @Override 
    protected Boolean doInBackground(URL... params) { 
     try { 
      mIcon_val = BitmapFactory.decodeStream(params[0].openConnection().getInputStream()); 
     } catch (IOException e) { 
      this.error = e; 
      return false; 
     } 
     return true; 
    } 

    @Override 
    protected void onPostExecute(Boolean success) { 
     super.onPostExecute(success); 
     if (success) { 
      image.setImageBitmap(mIcon_val); 
     } else { 
      image.setImageBitmap(defaultImage); 
     } 
    } 
}; 
try { 
    URL url = new URL(url); 
    asyncTask.execute(url); 
} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} 

对于这样的任务最好的现代化图书馆我的意见是Picasso由广场。它允许图像通过URL用一行代码加载到ImageView的:

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

Picasso允许无障碍的图像加载在你的应用程序经常在一行代码!

使用摇篮:

compile 'com.squareup.picasso:picasso:2.5.2' 

的代码只是一条线!图像加载Android上

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

许多常见的陷阱是由Picasso

  • 处理ImageView的回收和下载取消在适配器自动处理。
  • 复杂的图像转换与最小的内存使用。
  • 自动内存和磁盘缓存。

enter image description here

2。Glide图像加载和缓存库为Android专注于平滑滚动

使用摇篮:

repositories { 
    mavenCentral() // jcenter() works as well because it pulls from Maven Central 
} 

dependencies { 
    compile 'com.github.bumptech.glide:glide:3.7.0' 
    compile 'com.android.support:support-v4:19.1.0' 
} 

//对于一个简单的观点:

@Override public void onCreate(Bundle savedInstanceState) { 
    ... 
    ImageView imageView = (ImageView) findViewById(R.id.my_image_view); 

    Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView); 
} 

//对于一个简单的图片列表:

@Override public View getView(int position, View recycled, ViewGroup container) { 
     final ImageView myImageView; 
     if (recycled == null) { 
     myImageView = (ImageView) inflater.inflate(R.layout.my_image_view, container, false); 
     } else { 
     myImageView = (ImageView) recycled; 
     } 

     String url = myUrls.get(position); 

     Glide 
     .with(myFragment) 
     .load(url) 
     .centerCrop() 
     .placeholder(R.drawable.loading_spinner) 
     .crossFade() 
     .into(myImageView); 

     return myImageView; 
} 
+2

因此,如果url是localhost,意味着图像在像xampp这样的开发系统本地服务器数据库中,我仍然可以从url =获取图像。 – blackjack 2014-06-09 10:31:22

+3

这太棒了! – nemesisfixx 2014-08-13 11:08:25

+2

@blackjack - 从应用程序本地主机将是智能手机本身。要访问开发中的系统,智能手机和开发系统必须位于同一网络中,并且您必须使用该网络中开发系统的IP地址。 – Ridcully 2015-02-15 07:02:35

试试这种方式,希望这会帮助你解决你的问题。

这里我将解释如何使用“AndroidQuery”外部库以asyncTask的方式从url/server加载图像,并将加载的图像缓存到设备文件或缓存区域。

  • 下载“AndroidQuery”库from here
  • 复制/粘贴这个罐子项目的lib文件夹并添加这个库项目构建路径
  • 现在我展示演示,如何使用它。

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:gravity="center"> 

     <FrameLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 

      <ImageView 
       android:id="@+id/imageFromUrl" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:adjustViewBounds="true"/> 
      <ProgressBar 
       android:id="@+id/pbrLoadImage" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center"/> 

     </FrameLayout> 
    </LinearLayout> 

MainActivity.java

public class MainActivity extends Activity { 

private AQuery aQuery; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    aQuery = new AQuery(this); 
    aQuery.id(R.id.imageFromUrl).progress(R.id.pbrLoadImage).image("http://itechthereforeiam.com/wp-content/uploads/2013/11/android-gone-packing.jpg",true,true); 
} 
} 

Note : Here I just implemented common method to load image from url/server but you can use various types of method which can be provided by "AndroidQuery"to load your image easily.