2010-03-18 27 views
443

如何在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

回答

57

無論如何,人們會問我的意見,並將其發佈爲答案。我張貼。

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

144

你必須下載圖像首先

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

25

你也可以使用此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

10
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

71

我寫了一個類來處理這個問題,因爲它似乎在我的各種項目中經常需要:

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

9

我最近發現一個線程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

10

您好我有最簡單的代碼試試這個

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"/> 

試試這個

6
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside 
3
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; 
    } 
634

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

55

如果您是通過單擊按鈕加載圖像,上述接受的答案是非常好的,但是如果您在新活動中進行加載,則會凍結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

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

此代碼已經過測試,它完全正常工作。

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

這是一個較晚的答覆,如上面建議AsyncTask將會和谷歌搜索後有點我找到了一個更多的方式來解決這個問題。

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

我自己試過,我還沒有面對任何問題。

+0

這實際上是非常好的極簡主義!請記住,由於UI線程不允許網絡操作,因此需要在額外的'Thread'中運行。 – creativecreatorormaybenot 2018-03-08 13:02:31

5

這將幫助你......

定義的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; 
} 
2

Android的查詢可以處理爲你和更多(如緩存和加載進度)。

看看here

我認爲是最好的方法。

3

任何容器中工作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

3

版本與異常處理和異步任務:

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(); 
} 
6

對於這樣的任務最好的現代化圖書館我的意見是Picasso由廣場。它允許圖像通過URL用一行代碼加載到ImageView的:

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

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

3

試試這種方式,希望這會幫助你解決你的問題。

這裏我將解釋如何使用「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. 
相關問題