如何在Android中通过URL加载ImageView?
如何在ImageView
使用URL引用的ImageView
?
从Android开发者 :
// 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" />
你必须先下载图像
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中
1. 毕加索允许在应用程序中轻松加载图像 – 通常只需一行代码即可!
使用Gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
只需一行代码!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Android上图像加载的许多常见陷阱都是由毕加索自动处理的
- 处理ImageView回收并在适配器中下载取消。
- 复杂的图像转换与最小的内存使用。
- 自动内存和磁盘caching。
2. 滑翔 Android的图像加载和caching库专注于平滑滚动
使用Gradle:
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; }
我写了一个类来处理这个问题,因为在我的各个项目中这似乎是反复出现的需求:
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper将使用在URL中find的图像来填充ImageView。
该示例将执行Google图片search,并asynchronous加载/显示结果。
UrlImageViewHelper会自动下载,保存和caching所有的图像url的BitmapDrawables。 重复的url不会被加载到内存中两次。 位图内存是通过使用弱引用哈希表来pipe理的,所以一旦图像不再被你使用,它就会被自动收集。
无论如何,人们问我的意见,作为答复。 我发布。
URL newurl = new URL(photo_url_str); mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); profile_photo.setImageBitmap(mIcon_val);
谢谢。
上面接受的答案是很好的,如果你正在加载的图像基于一个button点击,但是如果你正在做一个新的活动,它冻结了一两个用户界面。 环顾四周,我发现一个简单的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);
其结果是一个快速加载的活动和imageview,显示了一秒之后取决于用户的networking速度。
你也可以使用这个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.comhttp://img.dovov.comdialog_buttons.png" />
在代码中:
final LoaderImageView image = new LoaderImageView(this, "http://developer.android.comhttp://img.dovov.comdialog_buttons.png");
并使用以下命令更新
image.setImageDrawable("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
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; } }
我最近在这里find了一个线程,因为我必须对图像做一个类似的事情,但是原理很简单,你可以在第一个示例类(jleedev)中看到。 你得到图像的inputstream(从网页)
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(); }
然后,您将图像存储为Drawable,您可以将其传递给ImageView(通过setImageDrawable)。 再从上面的代码片段看看整个线程。
InputStream is = fetch(urlString); Drawable drawable = Drawable.createFromStream(is, "src");
嗨,我有最简单的代码试试这个
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; } } }
main.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"/>
尝试这个
很多很好的信息在这里…我最近发现了一个名为SmartImageView的类,目前看起来工作得很好。 很容易纳入和使用。
http://loopj.com/android-smart-image-view/
https://github.com/loopj/android-smart-image-view
更新 :我写了一篇关于这个的博客文章 ,所以检查一下使用SmartImageView的帮助。
2ND更新 :我现在总是使用毕加索(见上),并强烈推荐它。 🙂
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
对我来说这样一个任务最好的现代化图书馆是毕加索广场。 它允许通过单行的URL将图像加载到ImageView:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
这将帮助你…
定义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; }
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; }
一个简单而干净的方法是使用开源库Prime 。
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);
这段代码经过testing,完全正常。
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());
在任何容器中处理imageView,如listview网格视图,正常布局
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 );
具有exception处理和asynchronous任务的版本:
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(); }
试试这样,希望这会帮助你解决你的问题。
在这里,我将解释如何使用“AndroidQuery”外部库以asyncTask方式从url / server加载图像,并将加载的图像caching到设备文件或caching区域。
- 从这里下载“AndroidQuery”库
- 复制/粘贴这个jar到项目lib文件夹,并将这个库添加到项目构buildpath
- 现在我演示如何使用它的演示。
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.
Android的查询可以为你处理和更多(如caching和加载进度)。
看看这里 。
我认为是最好的方法。
这是一个迟到的答复,正如上面提出的AsyncTask
将会和谷歌search后,我find了一个更多的方式来解决这个问题。
my_image_view.setImageDrawable(Drawable.createFromStream((InputStream)new URL(<String_url>).getContent(), "src"));
我自己尝试过,我还没有面对任何问题。