如何在ImageView
中使用通过URL引用的图片?
如何在ImageView
中使用通过URL引用的图片?
来自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" />
1. Picasso 允许在您的应用程序中轻松加载图像,通常只需一行代码!
使用 Gradle:
implementation 'com.squareup.picasso:picasso:(insert latest version)'
只需要一行代码!
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
2. Glide 是一款专注于实现流畅滚动的 Android 图片加载和缓存库。
使用 Gradle:
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
// For a simple view:
Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);
3. Fresco 是一款在 Android 应用程序中显示图像的强大系统。Fresco 负责图像加载和显示,因此您无需操心。
4. Coil 是一款由 Kotlin 协程支持的 Android 图像加载库。
implementation("io.coil-kt:coil:2.3.0")
要将图像加载到 ImageView
中,请使用 load 扩展函数:
imageView.load("https://example.com/image.jpg")
首先你需要先下载该图片
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 中。无论如何,人们要求我发表评论作为答案。 我正在发布。
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);
我编写了一个类来处理这个问题,因为在我的各种项目中似乎有这种常见需求:
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper可以填充一个ImageView,并显示从URL找到的图像。
该示例将执行Google Image Search并异步加载/显示结果。
UrlImageViewHelper将自动下载、保存和缓存所有图像URL BitmapDrawables。重复的URL不会被加载两次到内存中。使用弱引用哈希表管理位图内存,因此一旦您不再使用图像,它就会被自动垃圾回收。
如果您是通过按钮点击加载图像,上面的接受回答非常好。但是,如果您在一个新的活动中执行此操作,它会冻结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);
结果是一个快速加载的活动和一个ImageView,取决于用户的网络速度,后者会在一瞬间显示出来。
<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");
我认为这项任务中最好的现代库是由Square提供的 Picasso。它可以通过一行代码从URL加载图像到ImageView:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
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;
}
}
嗨,我有一段最简单的代码,请试试
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;
}
}
}
<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"/>
试试这个